forked from jquery/jquery
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware-mockserver.js
44 lines (39 loc) · 1.02 KB
/
middleware-mockserver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import url from "url";
import { coreMockserverHandler } from "./middleware-handlers.js";
/**
* Connect-compatible middleware factory for mocking server responses.
* Used by Ajax tests run in Node.
*/
export function MockserverMiddlewareFactory() {
/**
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} resp
* @param {Function} next Continue request handling
*/
return async function( req, resp, next ) {
const parsed = url.parse( req.url, /* parseQuery */ true );
const context = {
parsed,
url: req.url,
method: req.method,
headers: req.headers
};
try {
const response = await coreMockserverHandler( {
context,
originalReq: req
} );
if ( response === null ) {
next();
return;
}
resp.writeHead( response.status, response.headers );
resp.end( response.body );
} catch ( err ) {
// TODO this is needed because jtr doesn't await the middleware; we should fix that
console.error( err );
next( err );
}
};
}
export default MockserverMiddlewareFactory;