-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
58 lines (55 loc) · 1.71 KB
/
index.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
56
57
58
const helper = require('think-helper');
/**
* default options
*/
const defaultOptions = {
requestTimeout: 10 * 1000, // request timeout, default is 10s
requestTimeoutCallback: () => {}, // request timeout callback
sendPowerBy: true, // send powerby
sendResponseTime: true, // send response time
logRequest: true,
ignoreUrl:[]
};
/**
* send meta middleware
*/
module.exports = (options, app) => {
options = Object.assign({}, defaultOptions, options);
options.requestTimeout = helper.ms(options.requestTimeout);
return (ctx, next) => {
// set request timeout
if (helper.isFunction(options.requestTimeoutCallback)) {
ctx.res.setTimeout(options.requestTimeout, () => {
options.requestTimeoutCallback(ctx, options);
});
}
// send power by header
if (options.sendPowerBy && !ctx.res.headersSent) {
const version = app.think.version;
ctx.res.setHeader('X-Powered-By', `thinkjs-${version}`);
}
// send response time header
if (options.sendResponseTime || options.logRequest) {
const startTime = Date.now();
let err;
return next().catch(e => {
err = e;
}).then(() => {
const endTime = Date.now();
if (options.sendResponseTime && !ctx.res.headersSent) {
ctx.res.setHeader('X-Response-Time', `${endTime - startTime}ms`);
}
if (options.logRequest) {
process.nextTick(() => {
if(!options.ignoreUrl.includes(ctx.url)){
app.think.logger.info(`${ctx.method} ${ctx.url} ${ctx.status} ${endTime - startTime}ms`);
}
});
}
if (err) return Promise.reject(err);
});
} else {
return next();
}
};
};