-
Notifications
You must be signed in to change notification settings - Fork 568
/
middleware.ts
73 lines (69 loc) 路 1.89 KB
/
middleware.ts
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
import { Middleware, Config, MidwayFrameworkType } from '@midwayjs/core';
import { toHTML } from './html';
import { CodeDyeOptions } from './interface';
import { asyncRunWrapper } from './reqInfo';
@Middleware()
export class CodeDyeMW {
@Config('codeDye')
codeDye: CodeDyeOptions;
resolve(app) {
if (app.getFrameworkType() === MidwayFrameworkType.WEB_EXPRESS) {
return async (req: any, res: any, next: any) => {
return this.compatibleMiddleware(req, res, next);
};
} else {
return async (ctx, next) => {
return this.compatibleMiddleware(ctx.request, ctx, next);
};
}
}
check(request) {
let outputType;
if (
this.codeDye.matchQueryKey &&
request.query[this.codeDye.matchQueryKey]
) {
outputType = request.query[this.codeDye.matchQueryKey];
} else if (
this.codeDye.matchHeaderKey &&
request.headers[this.codeDye.matchHeaderKey]
) {
outputType = request.headers[this.codeDye.matchQueryKey];
}
if (!outputType) {
return false;
}
return outputType;
}
async compatibleMiddleware(request, response, next) {
const reqInfo = {
call: [],
};
const outputType = this.check(request);
if (!outputType) {
return next();
}
return asyncRunWrapper(this.codeDye, reqInfo, async () => {
const res = await next();
const reqInfoJSON = JSON.stringify(
reqInfo,
(key, value) => {
if (key === 'codeDyeConfig' || key === 'codeDyeParent') {
return;
}
return value;
},
0
);
if (outputType === 'log') {
console.log(reqInfoJSON);
} else if (outputType === 'html') {
response.set('Content-Type', 'text/html');
return toHTML(reqInfo.call);
} else if (outputType === 'json') {
return reqInfoJSON;
}
return res;
});
}
}