1 | import Whisper from "@36node/whisper";
|
2 |
|
3 | import Request from "./request";
|
4 | import Response from "./response";
|
5 | import Protocol from "./protocol";
|
6 | import logger from "./lib/log";
|
7 |
|
8 | const app = new Whisper();
|
9 | const protocol = new Protocol();
|
10 |
|
11 | const log = async (ctx, next) => {
|
12 |
|
13 | const startedAt = Date.now();
|
14 |
|
15 | await next();
|
16 |
|
17 |
|
18 | const endAt = Date.now();
|
19 | logger.info(ctx.data);
|
20 | logger.info("request: ");
|
21 | logger.info(ctx.req);
|
22 | logger.info("response: ");
|
23 | logger.info(ctx.res);
|
24 | logger.info(
|
25 | `session ${ctx.session.id}: seq ${ctx.no} success ${endAt - startedAt} ms`
|
26 | );
|
27 | };
|
28 |
|
29 | const handleFrame = async (ctx, next) => {
|
30 |
|
31 | const json = protocol.parse(ctx.data);
|
32 | ctx.req = new Request(json);
|
33 |
|
34 | await next();
|
35 |
|
36 |
|
37 | ctx.res = new Response(json.body);
|
38 | ctx.send(protocol.build(ctx.res));
|
39 | };
|
40 |
|
41 | app.use(log);
|
42 | app.use(handleFrame);
|
43 |
|
44 | app.on("close", session => {
|
45 | logger.info(`session ${session.id}: closed`);
|
46 | });
|
47 |
|
48 | app.on("timeout", session => {
|
49 | logger.info(`session ${session.id}: timeout`);
|
50 | });
|
51 |
|
52 | app.on("end", session => {
|
53 | logger.info(`session ${session.id}: end`);
|
54 | });
|
55 |
|
56 | app.on("error", session => {
|
57 | logger.info(`session ${session.id}: error`);
|
58 | });
|
59 |
|
60 | export default app;
|