mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
36 lines (35 loc) • 1.42 kB
JavaScript
;
import { readFileSync, existsSync } from 'fs-extra';
import { absifyPath } from '../utils/path';
import { isNil } from '../utils/is';
import { PKG_NAME } from '../consts';
const ICON_BASE64 = 'data:image/x-icon;base64,8J+YgQ==';
const ICON_MIME = 'image/x-icon';
export default function favicon(faviconPath, options) {
faviconPath = absifyPath(faviconPath);
const isExisted = existsSync(faviconPath);
const iconFile = isExisted ? readFileSync(faviconPath) : ICON_BASE64;
let { maxAge, mime } = options || {};
maxAge = isNil(maxAge) ? 86400000 : Math.min(Math.max(0, maxAge), 31556926000);
mime = isExisted ? mime : ICON_MIME;
const cacheControl = `public, max-age=${(maxAge / 1000) | 0}`;
return async function (ctx, next) {
const { path, method } = ctx || {};
if (['/favicon.ico', '/favicon.png', '/favicon.svg'].some(p => p === path)) {
ctx.skipDefaultMock = true;
if (!['GET', 'HEAD'].includes(method)) {
ctx.status = 'OPTIONS' == method ? 200 : 405;
ctx.set('Allow', 'GET, HEAD, OPTIONS');
}
else {
ctx.set('X-Powered-By', PKG_NAME);
ctx.set('Cache-Control', cacheControl);
ctx.type = mime || ICON_MIME;
ctx.body = iconFile;
}
}
else {
return next();
}
};
}