test-server.ts
2.65 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import * as bodyParser from "body-parser";
import * as express from "express";
import { Server } from "http";
import { join } from "path";
import { writeFileSync } from "fs";
import {
JSONParseError,
SignatureValidationFailed,
} from "../../lib/exceptions";
import * as finalhandler from "finalhandler";
let server: Server = null;
function listen(port: number, middleware?: express.RequestHandler) {
const app = express();
if (middleware) {
app.use((req: express.Request, res, next) => {
if (req.path === "/mid-text") {
bodyParser.text({ type: "*/*" })(req, res, next);
} else if (req.path === "/mid-buffer") {
bodyParser.raw({ type: "*/*" })(req, res, next);
} else if (req.path === "/mid-rawbody") {
bodyParser.raw({ type: "*/*" })(req, res, err => {
if (err) return next(err);
(req as any).rawBody = req.body;
delete req.body;
next();
});
} else if (req.path === "/mid-json") {
bodyParser.json({ type: "*/*" })(req, res, next);
} else {
next();
}
});
app.use(middleware);
}
// write request info
app.use((req: express.Request, res, next) => {
const request: any = ["headers", "method", "path", "query"].reduce(
(r, k) => Object.assign(r, { [k]: (req as any)[k] }),
{},
);
if (Buffer.isBuffer(req.body)) {
request.body = req.body.toString("base64");
} else {
request.body = req.body;
}
writeFileSync(
join(__dirname, "request.json"),
JSON.stringify(request, null, 2),
);
next();
});
// return an empty object for others
app.use((req, res) => res.json({}));
app.use(
(err: Error, req: express.Request, res: express.Response, next: any) => {
if (err instanceof SignatureValidationFailed) {
res.status(401).send(err.signature);
return;
} else if (err instanceof JSONParseError) {
res.status(400).send(err.raw);
return;
}
// https://github.com/expressjs/express/blob/2df1ad26a58bf51228d7600df0d62ed17a90ff71/lib/application.js#L162
// express will record error in console when
// there is no other handler to handle error & it is in test environment
// use final handler the same as in express application.js
finalhandler(req, res)(err);
},
);
return new Promise(resolve => {
server = app.listen(port, () => resolve());
});
}
function close() {
return new Promise(resolve => {
if (!server) {
resolve();
}
server.close(() => resolve());
});
}
export { listen, close };