@samitouri / QOSami-HFS / commits / 602f149d

small optimization on mime types

Massimo Melina committed Nov 21, 2023 at 22:05 UTC 602f149df327e8cacbc3fc70ad7cf01f1bff091e
2 files changed +8 -4
src/config.ts
+1 -1
@@ -56,7 +56,7 @@ export const currentVersion = new Version(VERSION)
56 const configVersion = defineConfig('version', VERSION, v => new Version(v))
57
58 type Subscriber<T,R=void> = (v:T, more: { was?: T, version?: Version, defaultValue: T, k: string }) => R
59 -export function defineConfig<T, CT=T>(k: string, defaultValue: T, compiler?: Subscriber<T,CT>) {
59 +export function defineConfig<T, CT=unknown>(k: string, defaultValue: T, compiler?: Subscriber<T,CT>) {
60 configProps[k] = { defaultValue }
61 type Updater = (currentValue:T) => T
62 let compiled = compiler?.(defaultValue, { k, version: currentVersion, defaultValue })
src/serveFile.ts
+7 -3
@@ -7,7 +7,7 @@ import { HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_METHOD_NOT_ALLOWED, HTTP_NO_CONT
7 import { getNodeName, VfsNode } from './vfs'
8 import mimetypes from 'mime-types'
9 import { defineConfig } from './config'
10 -import { matches } from './misc'
10 +import { Dict, makeMatcher, matches } from './misc'
11 import _ from 'lodash'
12 import path from 'path'
13 import { promisify } from 'util'
@@ -38,13 +38,17 @@ export function serveFileNode(ctx: Koa.Context, node: VfsNode) {
38 }
39 }
40
41 -const mimeCfg = defineConfig<Record<string,string>>('mime', { '*': MIME_AUTO })
41 +const mimeCfg = defineConfig<Dict<string>, (name: string) => string | undefined>('mime', { '*': MIME_AUTO }, obj => {
42 + const matchers = Object.keys(obj).map(k => makeMatcher(k))
43 + const values = Object.values(obj)
44 + return (name: string) => values[matchers.findIndex(matcher => matcher(name))]
45 +})
46
47 export async function serveFile(ctx: Koa.Context, source:string, mime?:string, content?: string | Buffer) {
48 if (!source)
49 return
50 const fn = path.basename(source)
47 - mime = mime ?? _.find(mimeCfg.get(), (v,k) => matches(fn, k))
51 + mime = mime ?? mimeCfg.compiled()(fn)
52 if (mime === MIME_AUTO)
53 mime = mimetypes.lookup(source) || ''
54 if (mime)