mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
30 lines (29 loc) • 1.43 kB
JavaScript
;
import { readFileSync } from 'fs-extra';
import { Debugger } from '../utils/print';
import { ASSET_TPL_HTML_404_PATH } from '../root';
export default function notFound() {
Debugger.log('mdw-404: init...');
const html = readFileSync(ASSET_TPL_HTML_404_PATH, 'utf-8');
return async function (ctx, next) {
const { routePath, mockRelPath, request, url } = ctx || {};
Debugger.log('mdw-404: >>', routePath);
await next();
if (ctx.status === 404 && !ctx.body) {
const { accept } = request.headers || {};
if (accept.includes('text/html') || accept.includes('application/xhtml+xml')) {
ctx.set('Content-Type', 'text/html');
ctx.body = html.replace('<%= detailMsg %>', `The Mock-data( <i></i> )${mockRelPath} is not found!!!`);
}
else if (accept.includes('application/json')) {
ctx.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ code: 404, data: '404 Not Found', msg: `Target request '${url}' was not found!` });
}
else {
ctx.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ code: 404, data: '404 Not Found', msg: `Target request ${routePath} (${accept}) was not found!` });
}
}
Debugger.log('mdw-404: <<', routePath);
};
}