@schmock/express 2.1.3 → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -147
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,147 +1 @@
|
|
|
1
|
-
/// <reference path="../../core/schmock.d.ts" />
|
|
2
|
-
import { isRouteNotFound, SchmockError, toHttpMethod } from "@schmock/core";
|
|
3
|
-
/**
|
|
4
|
-
* Convert Schmock response to Express response
|
|
5
|
-
*/
|
|
6
|
-
function schmockToExpressResponse(schmockResponse, res) {
|
|
7
|
-
// Set status code
|
|
8
|
-
if (schmockResponse.status != null) {
|
|
9
|
-
res.status(schmockResponse.status);
|
|
10
|
-
}
|
|
11
|
-
// Set headers
|
|
12
|
-
if (schmockResponse.headers) {
|
|
13
|
-
Object.entries(schmockResponse.headers).forEach(([key, value]) => {
|
|
14
|
-
if (typeof value === "string") {
|
|
15
|
-
res.set(key, value);
|
|
16
|
-
}
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
// Send body
|
|
20
|
-
if (schmockResponse.body !== undefined) {
|
|
21
|
-
if (typeof schmockResponse.body === "string") {
|
|
22
|
-
res.send(schmockResponse.body);
|
|
23
|
-
}
|
|
24
|
-
else {
|
|
25
|
-
res.json(schmockResponse.body);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
else {
|
|
29
|
-
res.end();
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Default header transformer
|
|
34
|
-
*/
|
|
35
|
-
function defaultTransformHeaders(headers) {
|
|
36
|
-
return Object.fromEntries(Object.entries(headers)
|
|
37
|
-
.map(([key, value]) => [key, Array.isArray(value) ? value[0] : value])
|
|
38
|
-
.filter((entry) => typeof entry[1] === "string"));
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Default query transformer
|
|
42
|
-
*/
|
|
43
|
-
function defaultTransformQuery(query) {
|
|
44
|
-
const result = {};
|
|
45
|
-
for (const [key, value] of Object.entries(query)) {
|
|
46
|
-
if (typeof value === "string") {
|
|
47
|
-
result[key] = value;
|
|
48
|
-
}
|
|
49
|
-
else if (Array.isArray(value)) {
|
|
50
|
-
result[key] = value[0] ? String(value[0]) : "";
|
|
51
|
-
}
|
|
52
|
-
else if (value != null) {
|
|
53
|
-
result[key] = String(value);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
return result;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Convert a Schmock mock instance to Express middleware
|
|
60
|
-
*/
|
|
61
|
-
export function toExpress(mock, options = {}) {
|
|
62
|
-
const { errorFormatter, passErrorsToNext = true, transformHeaders = defaultTransformHeaders, transformQuery = defaultTransformQuery, beforeRequest, beforeResponse, } = options;
|
|
63
|
-
return async (req, res, next) => {
|
|
64
|
-
try {
|
|
65
|
-
// Skip non-standard HTTP methods (e.g. WebDAV PROPFIND, LOCK)
|
|
66
|
-
let method;
|
|
67
|
-
try {
|
|
68
|
-
method = toHttpMethod(req.method);
|
|
69
|
-
}
|
|
70
|
-
catch {
|
|
71
|
-
return next();
|
|
72
|
-
}
|
|
73
|
-
// Run request interceptor if provided
|
|
74
|
-
let requestData = {
|
|
75
|
-
method,
|
|
76
|
-
path: req.path,
|
|
77
|
-
headers: transformHeaders(req.headers),
|
|
78
|
-
body: req.body,
|
|
79
|
-
query: transformQuery(req.query),
|
|
80
|
-
};
|
|
81
|
-
if (beforeRequest) {
|
|
82
|
-
const intercepted = await beforeRequest(req, res);
|
|
83
|
-
if (intercepted) {
|
|
84
|
-
requestData = {
|
|
85
|
-
...requestData,
|
|
86
|
-
...intercepted,
|
|
87
|
-
method: toHttpMethod(intercepted.method || requestData.method),
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
// Handle request with Schmock
|
|
92
|
-
let schmockResponse = await mock.handle(requestData.method, requestData.path, {
|
|
93
|
-
headers: requestData.headers,
|
|
94
|
-
body: requestData.body,
|
|
95
|
-
query: requestData.query,
|
|
96
|
-
});
|
|
97
|
-
// Detect ROUTE_NOT_FOUND responses and pass to next middleware
|
|
98
|
-
if (isRouteNotFound(schmockResponse)) {
|
|
99
|
-
next();
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
// Run response interceptor if provided
|
|
103
|
-
if (beforeResponse) {
|
|
104
|
-
const intercepted = await beforeResponse(schmockResponse, req, res);
|
|
105
|
-
if (intercepted) {
|
|
106
|
-
schmockResponse = intercepted;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
// Auto-route schmock's internal 500 ({ error, code }) through
|
|
110
|
-
// errorFormatter so the formatter sees every error path, not just
|
|
111
|
-
// those caught here. Mirrors the Angular adapter behaviour.
|
|
112
|
-
if (errorFormatter &&
|
|
113
|
-
schmockResponse.status === 500 &&
|
|
114
|
-
schmockResponse.body !== null &&
|
|
115
|
-
typeof schmockResponse.body === "object" &&
|
|
116
|
-
"error" in schmockResponse.body &&
|
|
117
|
-
"code" in schmockResponse.body) {
|
|
118
|
-
const respBody = schmockResponse.body;
|
|
119
|
-
const errMsg = typeof respBody.error === "string" ? respBody.error : "Unknown error";
|
|
120
|
-
const formatted = errorFormatter(new Error(errMsg), req);
|
|
121
|
-
res.status(500).json(formatted);
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
// Convert and send Schmock response
|
|
125
|
-
schmockToExpressResponse(schmockResponse, res);
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
// Handle errors based on configuration
|
|
129
|
-
if (errorFormatter) {
|
|
130
|
-
// Fires for any Error from the handler/pipeline, not just
|
|
131
|
-
// SchmockError — matches the Angular adapter's behavior.
|
|
132
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
133
|
-
const formatted = errorFormatter(err, req);
|
|
134
|
-
res.status(500).json(formatted);
|
|
135
|
-
}
|
|
136
|
-
else if (passErrorsToNext) {
|
|
137
|
-
next(error);
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
res.status(500).json({
|
|
141
|
-
error: error instanceof Error ? error.message : "Internal Server Error",
|
|
142
|
-
code: error instanceof SchmockError ? error.code : "INTERNAL_ERROR",
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
};
|
|
147
|
-
}
|
|
1
|
+
import{createRequire as a}from"node:module";var o=a(import.meta.url);var y=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];function g(V){return y.includes(V)}function j(V){let $=V.toUpperCase();if(!g($))throw Error(`Invalid HTTP method: "${V}"`);return $}function x(V){return V.endsWith("/")&&V!=="/"?V.slice(0,-1):V}function H(V){let{status:$,body:J}=V;return $===404&&J!==null&&typeof J==="object"&&"code"in J&&J.code==="ROUTE_NOT_FOUND"}function b(V){return Array.isArray(V)&&(V.length===2||V.length===3)&&typeof V[0]==="number"&&V[0]>=100&&V[0]<=599}function D(V){return V instanceof Error?V.message:"Unknown error"}class T extends Error{code;context;constructor(V,$,J){super(V);this.code=$;this.context=J;if(this.name="SchmockError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor)}}class P extends T{constructor(V,$){super(`Route not found: ${V} ${$}`,"ROUTE_NOT_FOUND",{method:V,path:$});this.name="RouteNotFoundError"}}class E extends T{constructor(V,$){super(`Invalid route key format: "${V}". ${$}`,"ROUTE_PARSE_ERROR",{routeKey:V,reason:$});this.name="RouteParseError"}}class C extends T{constructor(V,$){super(`Plugin "${V}" failed: ${$.message}`,"PLUGIN_ERROR",{pluginName:V,originalError:$});this.name="PluginError"}}class S extends T{constructor(V,$){super(`Invalid route definition for "${V}": ${$}`,"ROUTE_DEFINITION_ERROR",{routeKey:V,reason:$});this.name="RouteDefinitionError"}}function f(V){let $={};for(let[J,X]of Object.entries(V.headers))if(typeof X==="string")$[J]=X;return $}function R(V){let $={};return V.searchParams.forEach((J,X)=>{$[X]=J}),$}var s=10485760;function k(V,$,J=s){return new Promise((X,Y)=>{let G=[],L=0;V.on("error",Y),V.on("data",(Z)=>{if(L+=Z.length,L>J){V.destroy(),Y(Object.assign(Error("Request body too large"),{status:413}));return}G.push(Z)}),V.on("end",()=>{let Z=Buffer.concat(G).toString();if(!Z){X(void 0);return}if(($["content-type"]??"").includes("json"))try{X(JSON.parse(Z))}catch{X(Z)}else X(Z)})})}function v(V,$,J){let X={...$.headers,...J};if(!X["content-type"]&&$.body!==void 0&&typeof $.body!=="string")X["content-type"]="application/json";let Y=$.body===void 0?void 0:typeof $.body==="string"?$.body:JSON.stringify($.body);V.writeHead($.status,X),V.end(Y)}function t(V){let $=V.indexOf("?"),J=$===-1?V:V.slice(0,$);if(J.includes("://"))try{return new URL(J).pathname}catch{}if(!J.startsWith("/"))return`/${J}`;return J}function r(V){if(!V.includes("://"))return null;try{return new URL(V).origin}catch{return null}}function e(V){if(V.includes("://"))try{let $=new URL(V),J=$.pathname,X=J==="/"?"":J.replace(/\/$/,"");return{origin:$.origin,path:X}}catch{}return{origin:null,path:V.replace(/\/$/,"")}}function V0(V){let $=V.indexOf("?");if($===-1)return{};let J=new URLSearchParams(V.slice($+1)),X={};return J.forEach((Y,G)=>{X[G]=Y}),X}function $0(V,$){let J={},X=$?.headers??(V instanceof Request?V.headers:void 0);if(!X)return J;if(X instanceof Headers)X.forEach((Y,G)=>{J[G]=Y});else if(Array.isArray(X))for(let[Y,G]of X)J[Y.toLowerCase()]=G;else for(let Y of Object.keys(X))J[Y.toLowerCase()]=X[Y];return J}async function J0(V,$){let J=$?.body??(V instanceof Request?V.body:null);if(J===null||J===void 0)return;if(typeof J==="string")try{return JSON.parse(J)}catch{return J}if(J instanceof URLSearchParams){let X={};return J.forEach((Y,G)=>{X[G]=Y}),X}if(V instanceof Request&&!$?.body&&V.body)try{return await V.clone().json()}catch{try{return await V.clone().text()}catch{return}}return}function q(V,$={}){let{baseUrl:J,passthrough:X=!0,beforeRequest:Y,beforeResponse:G,errorFormatter:L}=$,Z=globalThis.fetch,_=!0;return globalThis.fetch=async(A,W)=>{let z=A instanceof Request?A.url:A instanceof URL?A.href:A,B=t(z);if(J){let{origin:K,path:U}=e(J);if(K){if(r(z)!==K)return Z(A,W)}if(U){if(!(B===U||B.startsWith(`${U}/`)))return Z(A,W)}}let O=A instanceof Request?A.method:W?.method??"GET",Q=$0(A,W),N=V0(z),F=await J0(A,W),M={method:O,path:B,headers:Q,body:F,query:N};try{if(Y){let I=await Y(M);if(I)M=I}let K=await V(j(M.method),M.path,{headers:M.headers,body:M.body,query:M.query});if(H(K)){if(X)return Z(A,W);return new Response(JSON.stringify({error:"No matching mock route found",code:"ROUTE_NOT_FOUND"}),{status:404,headers:{"content-type":"application/json"}})}let U=K;if(G){let I=await G(U,M);if(I)U=I}let w=new Headers(U.headers);if(!w.has("content-type")&&U.body!==null&&U.body!==void 0)w.set("content-type","application/json");let n=U.body===null||U.body===void 0?null:typeof U.body==="string"?U.body:JSON.stringify(U.body);return new Response(n,{status:U.status,headers:w})}catch(K){if(L){let U=L(K instanceof Error?K:Error(String(K)));return new Response(JSON.stringify(U),{status:500,headers:{"content-type":"application/json"}})}throw K}},{restore(){if(_)globalThis.fetch=Z,_=!1},get active(){return _}}}function d(V){let $=V.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) (.+)$/);if(!$)throw new E(V,'Expected format: "METHOD /path" (e.g., "GET /users")');let[,J,X]=$,Y=[],G=X.split(/(:[a-zA-Z0-9_-]+)/g).map((Z)=>{let _=Z.match(/^:([a-zA-Z0-9_-]+)$/);if(_)return Y.push(_[1]),"([^/]+)";return Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join(""),L=new RegExp(`^${G}$`);return{method:j(J),path:X,pattern:L,params:Y}}async function m(V,$,J,X){let Y=$,G=J;X.log("pipeline",`Running plugin pipeline for ${V.length} plugins`);for(let L of V){X.log("pipeline",`Processing plugin: ${L.name}`);try{let Z=await L.process(Y,G);if(!Z?.context)throw Error(`Plugin ${L.name} didn't return valid result`);if(Y=Z.context,Z.response!==void 0&&(G===void 0||G===null))X.log("pipeline",`Plugin ${L.name} generated response`),G=Z.response;else if(Z.response!==void 0&&G!==void 0)X.log("pipeline",`Plugin ${L.name} transformed response`),G=Z.response}catch(Z){if(X.log("pipeline",`Plugin ${L.name} failed: ${D(Z)}`),L.onError)try{let A=Z instanceof Error?Z:Error(D(Z)),W=await L.onError(A,Y);if(W){if(X.log("pipeline",`Plugin ${L.name} handled error`),W instanceof Error)throw new C(L.name,W);if(typeof W==="object"&&W!==null&&"status"in W){G=W;break}}}catch(A){if(A instanceof C)throw A;X.log("pipeline",`Plugin ${L.name} error handler failed: ${D(A)}`)}let _=Z instanceof Error?Z:Error(D(Z));throw new C(L.name,_)}}return{context:Y,response:G}}function X0(V){return typeof V==="object"&&V!==null&&"status"in V&&"body"in V}function c(V,$){let J=200,X=V,Y={},G=!1;if(X0(V))return{status:V.status,body:V.body,headers:V.headers||{}};if(b(V))[J,X,Y={}]=V,G=!0;if(X===null||X===void 0){if(!G)J=J===200?204:J;X=void 0}if(!Y["content-type"]&&$.contentType&&!G){if(Y["content-type"]=$.contentType,$.contentType==="text/plain"&&X!==void 0){if(typeof X==="object"&&!Buffer.isBuffer(X))X=JSON.stringify(X);else if(typeof X!=="string")X=String(X)}}return{status:J,body:X,headers:Y}}function l(V){return typeof V==="function"}function h(V,$,J,X){let Y=J.get(`${V} ${x($)}`);if(Y)return Y;for(let G of X)if(G.method===V&&G.params.length>0&&G.pattern.test($))return G;return}function i(V,$){let J=$.match(V.pattern);if(!J)return{};let X={};return V.params.forEach((Y,G)=>{X[Y]=J[G+1]}),X}class u{enabled;constructor(V=!1){this.enabled=V}log(V,$,J){if(!this.enabled)return;let Y=`[${new Date().toISOString()}] [SCHMOCK:${V.toUpperCase()}]`;if(J)console.log(`${Y} ${$}`,J);else console.log(`${Y} ${$}`)}time(V){if(!this.enabled)return;console.time(`[SCHMOCK] ${V}`)}timeEnd(V){if(!this.enabled)return;console.timeEnd(`[SCHMOCK] ${V}`)}}class p{globalConfig;routes=[];staticRoutes=new Map;plugins=[];logger;requestHistory=[];callableRef;server;serverInfo;interceptHandle=null;listeners=new Map;constructor(V={}){this.globalConfig=V;if(this.logger=new u(V.debug||!1),V.debug)this.logger.log("config","Debug mode enabled");this.logger.log("config","Callable mock instance created",{debug:V.debug,namespace:V.namespace,delay:V.delay})}defineRoute(V,$,J){if(!J.contentType)if(typeof $==="function")J.contentType="application/json";else if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")J.contentType="text/plain";else if(Buffer.isBuffer($))J.contentType="application/octet-stream";else J.contentType="application/json";if(typeof $!=="function"&&J.contentType==="application/json")try{JSON.stringify($)}catch(L){throw new S(V,"Generator data is not valid JSON but contentType is application/json")}let X=d(V);if(this.routes.find((L)=>L.method===X.method&&L.path===X.path))return this.logger.log("warning",`Duplicate route: ${V} — first registration wins`),this;let G={pattern:X.pattern,params:X.params,method:X.method,path:X.path,generator:$,config:J};if(this.routes.push(G),X.params.length===0){let L=`${X.method} ${x(X.path)}`;this.staticRoutes.set(L,G)}return this.logger.log("route",`Route defined: ${V}`,{contentType:J.contentType,generatorType:typeof $,hasParams:X.params.length>0}),this}setCallableRef(V){this.callableRef=V}pipe(V){if(this.plugins.push(V),this.logger.log("plugin",`Registered plugin: ${V.name}@${V.version||"unknown"}`,{name:V.name,version:V.version,hasProcess:typeof V.process==="function",hasOnError:typeof V.onError==="function"}),V.install&&this.callableRef)V.install(this.callableRef);return this}history(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$));return[...this.requestHistory]}called(V,$){if(V||$)return this.requestHistory.some((J)=>(!V||J.method===V)&&(!$||J.path===$));return this.requestHistory.length>0}callCount(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$)).length;return this.requestHistory.length}lastRequest(V,$){if(V||$){let J=this.requestHistory.filter((X)=>(!V||X.method===V)&&(!$||X.path===$));return J[J.length-1]}return this.requestHistory[this.requestHistory.length-1]}getRoutes(){return this.routes.map((V)=>({method:V.method,path:V.path,hasParams:V.params.length>0}))}getState(){return{...this.globalConfig.state||{}}}on(V,$){let J=this.listeners.get(V);if(!J)J=new Set,this.listeners.set(V,J);return J.add($),this}off(V,$){return this.listeners.get(V)?.delete($),this}emit(V,$){let J=this.listeners.get(V);if(J)for(let X of J)X($)}reset(){if(this.interceptHandle?.restore(),this.interceptHandle=null,this.close(),this.routes=[],this.staticRoutes.clear(),this.plugins=[],this.requestHistory=[],this.listeners.clear(),this.globalConfig.state)for(let V of Object.keys(this.globalConfig.state))delete this.globalConfig.state[V];this.logger.log("lifecycle","Mock fully reset")}resetHistory(){this.requestHistory=[],this.logger.log("lifecycle","Request history cleared")}resetState(){if(this.globalConfig.state)for(let V of Object.keys(this.globalConfig.state))delete this.globalConfig.state[V];this.logger.log("lifecycle","State cleared")}listen(V=0,$="127.0.0.1"){if(this.server)throw new T("Server is already running","SERVER_ALREADY_RUNNING");return import("node:http").then(({createServer:J})=>this.#V(J,V,$))}#V(V,$,J){let X=V((Y,G)=>{(async()=>{let Z=new URL(Y.url??"/",`http://${Y.headers.host}`),_=j(Y.method??"GET"),A=Z.pathname,W=f(Y),z=R(Z),B=await k(Y,W),O=await this.handle(_,A,{headers:W,body:B,query:z});v(G,O)})().catch((Z)=>{if(!G.headersSent)G.writeHead(500,{"content-type":"application/json"});G.end(JSON.stringify({error:Z instanceof Error?Z.message:"Internal Server Error",code:"SERVER_ERROR"}))})});return this.server=X,new Promise((Y,G)=>{X.on("error",G),X.listen($,J,()=>{let L=X.address(),Z=L!==null&&typeof L==="object"?L.port:$;this.serverInfo={port:Z,hostname:J},this.logger.log("server",`Listening on ${J}:${Z}`),Y(this.serverInfo)})})}close(){if(!this.server)return;this.server.closeAllConnections(),this.server.close(),this.server=void 0,this.serverInfo=void 0,this.logger.log("server","Server stopped")}intercept(V){if(this.interceptHandle?.active)throw new T("Already intercepting. Call restore() first.","ALREADY_INTERCEPTING");return this.interceptHandle=q(($,J,X)=>this.handle($,J,X),V),this.interceptHandle}async handle(V,$,J){let X=performance.now(),Y=this.globalConfig.debug?crypto.randomUUID():"",G=J?.query||{},L=J?.headers||{};this.logger.log("request",`[${Y}] ${V} ${$}`,{headers:L,query:G,bodyType:J?.body?typeof J.body:"none"}),this.logger.time(`request-${Y}`),this.emit("request:start",{method:V,path:$,headers:L});try{let Z=$;if(this.globalConfig.namespace&&this.globalConfig.namespace!=="/"){let N=this.globalConfig.namespace.startsWith("/")?this.globalConfig.namespace:`/${this.globalConfig.namespace}`,F=$.startsWith("/")?$:`/${$}`;if(!(F===N||F.startsWith(N.endsWith("/")?N:`${N}/`))){this.logger.log("route",`[${Y}] Path doesn't match namespace ${N}`);let U=new P(V,$),w={status:404,body:{error:U.message,code:U.code},headers:{}};return this.emit("request:end",{method:V,path:$,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),w}let K=F.slice(N.length);Z=K.startsWith("/")?K:`/${K}`}let _=h(V,Z,this.staticRoutes,this.routes);if(!_){this.logger.log("route",`[${Y}] No route found for ${V} ${Z}`),this.emit("request:notfound",{method:V,path:Z});let N=new P(V,$),F={status:404,body:{error:N.message,code:N.code},headers:{}};return this.emit("request:end",{method:V,path:Z,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),F}this.logger.log("route",`[${Y}] Matched route: ${V} ${_.path}`);let A=i(_,Z);this.emit("request:match",{method:V,path:Z,routePath:_.path,params:A});let W={method:V,path:Z,params:A,query:G,headers:L,body:J?.body,state:this.globalConfig.state||{}},z;if(l(_.generator))z=await _.generator(W);else z=_.generator;let B={path:Z,route:_.config,method:V,params:A,query:G,headers:L,body:J?.body,state:new Map,routeState:this.globalConfig.state||{}};try{let N=await m(this.plugins,B,z,this.logger);B=N.context,z=N.response}catch(N){throw this.logger.log("error",`[${Y}] Plugin pipeline error: ${D(N)}`),N}let O=c(z,_.config);await this.applyDelay(_.config.delay),this.requestHistory.push({method:V,path:Z,params:A,query:G,headers:L,body:J?.body,timestamp:Date.now(),response:{status:O.status,body:O.body}});let Q=this.globalConfig.maxHistorySize;if(typeof Q==="number"&&Q>=0&&this.requestHistory.length>Q)this.requestHistory.splice(0,this.requestHistory.length-Q);return this.emit("request:end",{method:V,path:Z,status:O.status,duration:performance.now()-X}),this.logger.log("response",`[${Y}] Sending response ${O.status}`,{status:O.status,headers:O.headers,bodyType:typeof O.body}),this.logger.timeEnd(`request-${Y}`),O}catch(Z){this.logger.log("error",`[${Y}] Error processing request: ${D(Z)}`,Z);let _={status:500,body:{error:D(Z),code:Z instanceof T?Z.code:"INTERNAL_ERROR"},headers:{}};return await this.applyDelay(),this.emit("request:end",{method:V,path:$,status:500,duration:performance.now()-X}),this.logger.log("error",`[${Y}] Returning error response 500`),this.logger.timeEnd(`request-${Y}`),_}}async applyDelay(V){let $=V??this.globalConfig.delay;if(!$)return;let J=Array.isArray($)?Math.random()*($[1]-$[0])+$[0]:$;await new Promise((X)=>setTimeout(X,J))}}function Y0(V,$){if(V.status!=null)$.status(V.status);if(V.headers)Object.entries(V.headers).forEach(([J,X])=>{if(typeof X==="string")$.set(J,X)});if(V.body!==void 0)if(typeof V.body==="string")$.send(V.body);else $.json(V.body);else $.end()}function Z0(V){return Object.fromEntries(Object.entries(V).map(([$,J])=>[$,Array.isArray(J)?J[0]:J]).filter(($)=>typeof $[1]==="string"))}function G0(V){let $={};for(let[J,X]of Object.entries(V))if(typeof X==="string")$[J]=X;else if(Array.isArray(X))$[J]=X[0]?String(X[0]):"";else if(X!=null)$[J]=String(X);return $}function $1(V,$={}){let{errorFormatter:J,passErrorsToNext:X=!0,transformHeaders:Y=Z0,transformQuery:G=G0,beforeRequest:L,beforeResponse:Z}=$;return async(_,A,W)=>{try{let z;try{z=j(_.method)}catch{return W()}let B={method:z,path:_.path,headers:Y(_.headers),body:_.body,query:G(_.query)};if(L){let Q=await L(_,A);if(Q)B={...B,...Q,method:j(Q.method||B.method)}}let O=await V.handle(B.method,B.path,{headers:B.headers,body:B.body,query:B.query});if(H(O)){W();return}if(Z){let Q=await Z(O,_,A);if(Q)O=Q}if(J&&O.status===500&&O.body!==null&&typeof O.body==="object"&&"error"in O.body&&"code"in O.body){let Q=O.body,N=typeof Q.error==="string"?Q.error:"Unknown error",F=J(Error(N),_);A.status(500).json(F);return}Y0(O,A)}catch(z){if(J){let B=z instanceof Error?z:Error(String(z)),O=J(B,_);A.status(500).json(O)}else if(X)W(z);else A.status(500).json({error:z instanceof Error?z.message:"Internal Server Error",code:z instanceof T?z.code:"INTERNAL_ERROR"})}}}export{$1 as toExpress};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@schmock/express",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.4",
|
|
4
4
|
"description": "Express adapter for Schmock mock API generator",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"vitest": "^4.1.7"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@schmock/core": "^2.1.
|
|
39
|
+
"@schmock/core": "^2.1.4",
|
|
40
40
|
"express": "^4.18.0 || ^5.0.0"
|
|
41
41
|
},
|
|
42
42
|
"keywords": [
|