-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
55 lines (48 loc) · 1.22 KB
/
app.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
45
46
47
48
49
50
51
52
53
54
55
const express = require("express");
const morgan = require("morgan");
const proxy = require("express-http-proxy");
const app = express();
const port = 3000;
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
let routes = require('./routes.json');
if (process.argv.slice(2)?.length > 0) {
const path = process.argv[2];
try {
routes = require(path);
} catch(e) {
console.log(`Could not load routes from file [${path}]`, e);
return;
}
}
app.use(morgan("combined"));
Object.keys(routes).forEach((k) => {
({ forwardTo, method = "get" } = routes[k]);
if (forwardTo) {
({ path } = forwardTo);
app.use(
k,
proxy(forwardTo.host, {
proxyReqPathResolver: function (_) {
return path;
},
})
);
return;
}
app[method.toLowerCase()](k, async (_, res) => {
({ delay, statusCode, body } = routes[k]);
statusCode = statusCode ?? 200;
body = body ?? "empty body";
if (delay) {
await sleep(delay);
}
res.status(statusCode).set("Access-Control-Allow-Origin", "*").send(body);
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});