import DI, {DDNames} from "@gongt/ts-stl-library/DI"; import {RequestHandler, Response} from "express-serve-static-core"; import * as ServeStatic from "serve-static"; import {ServeStaticOptions} from "serve-static"; export type ServeStaticEx = ServeStaticOptions&StaticCORSOptions; export interface StaticCORSOptions { cors?: boolean; methods?: string[]; debugMode?: boolean; } export function createServeStatic(fsPath: string, options: ServeStaticEx = {}): RequestHandler { const resHeader: any = { // 'Access-Control-Allow-Origin': origins, // 'Access-Control-Expose-Headers': '', 'Access-Control-Max-Age': 3600, // only access control cache time // 'Access-Control-Allow-Credentials': '', // 'Access-Control-Allow-Headers': '', }; const isDebug = options.hasOwnProperty('debugMode')? options.debugMode : DI.get(DDNames.isDebugMode); if (isDebug) { resHeader['Cache-Control'] = 'must-revalidate'; } if (options.cors) { // TODO: cors resHeader['Access-Control-Allow-Origin'] = '*'; if (options.methods) { resHeader['Access-Control-Allow-Methods'] = options.methods.join(', '); } else { resHeader['Access-Control-Allow-Methods'] = '*'; } } const custom = options.setHeaders; if (custom) { options.setHeaders = (res: Response, path: string, stat: any) => { res.header(resHeader); custom(res, path, stat); }; } else { options.setHeaders = (res: Response) => res.header(resHeader); } if (/npm_modules|jspm_modules/.test(fsPath)) { if (!options.hasOwnProperty('maxAge')) { options.maxAge = isDebug? '1h' : '7d'; } if (!options.hasOwnProperty('etag')) { options.etag = true; } } else { if (!options.hasOwnProperty('maxAge')) { options.maxAge = isDebug? '0' : '1d'; } if (!options.hasOwnProperty('etag')) { options.etag = true; } } if (!options.hasOwnProperty('fallthrough')) { options.fallthrough = false; } return ServeStatic( fsPath, options, ); }