UNPKG

mihawk

Version:

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

26 lines (25 loc) 1.25 kB
'use strict'; import { readFileSync } from 'fs-extra'; import { ASSET_TPL_HTML_404_PATH } from '../root'; export default function notFound() { const html = readFileSync(ASSET_TPL_HTML_404_PATH, 'utf-8'); return async function (ctx, next) { const { routePath, mockRelPath, request, url } = ctx || {}; 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(&nbsp;<i></i>&nbsp;&nbsp;)${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!` }); } } }; }