UNPKG

aspida-mock

Version:

TypeScript friendly RESTful API mock for aspida

63 lines 2.77 kB
import { dataToURLString, } from 'aspida'; import callMockHandler, { hasMockHandler } from './callMockHandler'; export const mockMethods = (methods) => methods; export const mockMiddleware = (middleware) => middleware; export const printLog = (config, status) => { const searchString = dataToURLString(config.query || {}); console.log(`[mock] ${config.method}: ${config.path}${searchString ? `?${searchString}` : ''} => ${status}`); }; export const mockClient = (aspidaClient) => { let mockRoutes = []; let mockConfig; return { baseURL: aspidaClient.baseURL, fetch(baseURL, url, method, params, type) { if (!hasMockHandler(url, method, mockRoutes)) { return aspidaClient.fetch(baseURL, url, method, params, type); } const send = async () => { var _a; const customConfig = { path: url !== null && url !== void 0 ? url : '', method, query: params === null || params === void 0 ? void 0 : params.query, reqBody: params === null || params === void 0 ? void 0 : params.body, reqHeaders: params === null || params === void 0 ? void 0 : params.headers, }; const result = (_a = (await callMockHandler(customConfig, mockRoutes, mockConfig === null || mockConfig === void 0 ? void 0 : mockConfig.middleware))) !== null && _a !== void 0 ? _a : { status: 404 }; if (mockConfig === null || mockConfig === void 0 ? void 0 : mockConfig.log) printLog(customConfig, result.status); await new Promise(resolve => setTimeout(resolve, mockConfig === null || mockConfig === void 0 ? void 0 : mockConfig.delayMSec)); const res = { status: result.status, body: result.resBody, headers: result.resHeaders, }; if (result.status >= 400) { const err = new Error(`Request failed with status code ${result.status}`); err.response = res; throw err; } return res; }; return { send, json: send, text: send, arrayBuffer: send, blob: send, formData: send, }; }, attachRoutes(routes, config) { mockRoutes = routes; mockConfig = config; }, detachRoutes() { mockRoutes = []; mockConfig = undefined; }, }; }; export { callMockHandler, hasMockHandler }; //# sourceMappingURL=index.js.map