mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
32 lines (31 loc) • 1.41 kB
JavaScript
;
import { join } from 'path';
import dedupe from 'free-dedupe';
import { Debugger } from '../utils/print';
import { isMatchPatterns } from '../utils/str';
import { PKG_NAME } from '../consts';
import { unixifyPath } from '../utils/path';
export default function (options) {
Debugger.log('mdw-com: init...', options);
const { logConfig } = options || {};
let { ignoreRoutes } = logConfig || {};
ignoreRoutes = dedupe(ignoreRoutes || []).map(ignRt => ignRt.trim().replace(/\s+/g, ' '));
const needCheckIgnore = ignoreRoutes?.length > 0;
return async function common(ctx, next) {
const { method, path } = ctx;
const routePath = `${method.toUpperCase()} ${path}`;
const disableLogPrint = needCheckIgnore && (isMatchPatterns(routePath, ignoreRoutes) || isMatchPatterns(path, ignoreRoutes));
!disableLogPrint && console.log();
Debugger.log('mdw-com: >>', routePath);
ctx.mockRelPath = unixifyPath(join(method, path));
ctx.routePath = routePath;
ctx.disableLogPrint = disableLogPrint;
const startTime = Date.now();
await next();
const keepTime = `${Date.now() - startTime}ms`;
ctx.set('X-Mock-Time', keepTime);
ctx.set('Server-Timing', `inner;dur=${keepTime}`);
ctx.set('X-Powered-By', PKG_NAME);
Debugger.log(`mdw-com: << ${ctx.type}`, routePath);
};
}