UNPKG

mihawk

Version:

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

32 lines (31 loc) 1.25 kB
'use strict'; import Colors from 'color-cc'; import { Printer } from '../utils/print'; import { isMatchPatterns } from '../utils/str'; import { LOG_ARROW } from '../consts'; import { unixifyPath } from '../utils/path'; export default function (routes) { const needCheckRoutes = Object.keys(routes)?.length > 0; const routeKvEntries = needCheckRoutes ? Object.entries(routes) : []; return async function (ctx, next) { const { skipDefaultMock, mockRelPath, routePath, path } = ctx; if (skipDefaultMock || !needCheckRoutes) { await next(); } else { let matched = null; for (const [k, v] of routeKvEntries) { if (isMatchPatterns(path, k) || isMatchPatterns(routePath, k)) { matched = { route: k, mockFile: v }; break; } } if (matched && matched.mockFile) { const newMockRelPath = unixifyPath(matched.mockFile); Printer.log('mdw-routes:', `Reset route-logic: ${Colors.cyan(mockRelPath)} ${LOG_ARROW} ${Colors.green(newMockRelPath)} ↩️`); ctx.mockRelPath = newMockRelPath; } await next(); } }; }