mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
39 lines (38 loc) • 2.15 kB
JavaScript
;
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 root_1 = require("../root");
function notFound() {
const html = (0, fs_extra_1.readFileSync)(root_1.ASSET_TPL_HTML_404_PATH, 'utf-8');
return function (ctx, next) {
return __awaiter(this, void 0, void 0, function* () {
const { routePath, mockRelPath, request, url } = ctx || {};
yield 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!` });
}
}
});
};
}
exports.default = notFound;