-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (66 loc) · 2.25 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class RequestMonitor {
description () {
return 'Feeds traffic information to the `--verbose` output.'
}
middleware (config, lws) {
let requestId = 1
lws.server.on('request', (req, res) => {
req.requestId = requestId++
})
return async (ctx, next) => {
const util = require('util')
/* first, inspect the request */
const reqInfo = {
requestId: ctx.req.requestId,
method: ctx.req.method,
url: ctx.req.url,
headers: ctx.req.headers
}
if (ctx.request.rawBody) {
if (Object.keys(ctx.request.body).length) {
reqInfo.body = ctx.request.body
} else {
reqInfo.body = ctx.request.rawBody
}
} else {
const incomingBuffer = ctx.req._readableState.buffer
if (incomingBuffer.head && incomingBuffer.head.data.length) {
reqInfo.bodyHead = incomingBuffer.head.data.toString('utf8', 0, 1000)
}
}
ctx.app.emit('verbose', 'server.request', reqInfo)
/* next, inspect the response */
await next()
const resInfo = {
requestId: ctx.req.requestId,
statusCode: ctx.res.statusCode
}
const headers = (ctx.res.getHeaders && ctx.res.getHeaders()) || ctx.res._headers
if (headers) resInfo.headers = headers
if (ctx.body) resInfo.body = ctx.body
if (ctx.response.is('json')) {
try {
resInfo.body = JSON.parse(resInfo.body)
} catch (err) {}
}
const stream = require('stream')
if (resInfo.body instanceof stream.Readable) {
if (/text\/event-stream/.test(ctx.response.type)) {
resInfo.body[util.inspect.custom] = function (depth, options) {
return options.stylize('[ SSE event-stream ]', 'special')
}
} else if (ctx.body.path) {
resInfo.body[util.inspect.custom] = function (depth, options) {
return options.stylize(`[ ReadStream: ${ctx.body.path} ]`, 'special')
}
} else {
resInfo.body[util.inspect.custom] = function (depth, options) {
return options.stylize(`[ Readable Stream ]`, 'special')
}
}
}
ctx.app.emit('verbose', 'server.response', resInfo)
}
}
}
module.exports = RequestMonitor