UNPKG

mihawk

Version:

A tiny & simple mock server tool, support json,js,cjs,ts(typescript).

49 lines (48 loc) 2.36 kB
'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const fs_extra_1 = require("fs-extra"); const path_1 = require("../utils/path"); const is_1 = require("../utils/is"); const consts_1 = require("../consts"); const ICON_BASE64 = 'data:image/x-icon;base64,8J+YgQ=='; const ICON_MIME = 'image/x-icon'; function favicon(faviconPath, options) { faviconPath = (0, path_1.absifyPath)(faviconPath); const isExisted = (0, fs_extra_1.existsSync)(faviconPath); const iconFile = isExisted ? (0, fs_extra_1.readFileSync)(faviconPath) : ICON_BASE64; let { maxAge, mime } = options || {}; maxAge = (0, is_1.isNil)(maxAge) ? 86400000 : Math.min(Math.max(0, maxAge), 31556926000); mime = isExisted ? mime : ICON_MIME; const cacheControl = `public, max-age=${(maxAge / 1000) | 0}`; return function (ctx, next) { return __awaiter(this, void 0, void 0, function* () { 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', consts_1.PKG_NAME); ctx.set('Cache-Control', cacheControl); ctx.type = mime || ICON_MIME; ctx.body = iconFile; } } else { return next(); } }); }; } exports.default = favicon;