1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | const http_1 = __importDefault(require("http"));
|
7 | const log_1 = __importDefault(require("./log"));
|
8 | let storedPort = 0;
|
9 | let isDone = false;
|
10 | function mockServerMiddleware(app, port) {
|
11 | storedPort = port;
|
12 | if (isDone) {
|
13 | return;
|
14 | }
|
15 | let wasError = false;
|
16 | isDone = true;
|
17 | app.use((clientReq, clientRes, next) => {
|
18 | try {
|
19 | const options = {
|
20 | hostname: "localhost",
|
21 | port: storedPort,
|
22 | path: clientReq.url,
|
23 | method: clientReq.method,
|
24 | headers: clientReq.headers,
|
25 | };
|
26 | if (clientReq.url === "/" ||
|
27 | clientReq.url.startsWith("/?") ||
|
28 | clientReq.url.startsWith("?") ||
|
29 | !storedPort) {
|
30 | next();
|
31 | return;
|
32 | }
|
33 | const proxy = http_1.default.request(options, (res) => {
|
34 | wasError = false;
|
35 | if (res.statusCode === 404) {
|
36 | next();
|
37 | }
|
38 | else if (res) {
|
39 | clientRes.writeHead(res.statusCode || 200, res.headers);
|
40 | res.pipe(clientRes, {
|
41 | end: true,
|
42 | });
|
43 | }
|
44 | });
|
45 | clientReq
|
46 | .pipe(proxy, {
|
47 | end: true,
|
48 | })
|
49 | .on("error", (ex) => {
|
50 | if (!wasError) {
|
51 | wasError = true;
|
52 | if (ex.code === "ECONNREFUSED") {
|
53 | log_1.default.error(`Server is not available on ${ex.address}${ex.port ? `:${ex.port}` : ""}`);
|
54 | }
|
55 | else {
|
56 | log_1.default.error("", ex);
|
57 | }
|
58 | }
|
59 | next();
|
60 | });
|
61 | }
|
62 | catch (ex) {
|
63 | log_1.default.error(ex.toString());
|
64 | next();
|
65 | }
|
66 | });
|
67 | }
|
68 | exports.default = mockServerMiddleware;
|