-
Notifications
You must be signed in to change notification settings - Fork 1
/
morgan-res-body.js
73 lines (58 loc) · 1.6 KB
/
morgan-res-body.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
// morgan-res-body @ npm, a simple morgan plugin for response body.
//refer https://thewebdev.info/2022/03/06/how-to-log-the-response-body-with-express/
/*
.createMiddleware(options)
create a middleware function for express
options
skip
a function like (req, res)=>{...},
return true to indicate to skip the request.
bufferName
a property name for saving body buffer in res, default "bodyBuffer".
*/
function createMiddleware(options) {
var skip = options?.skip;
var bufferName = options?.bufferName || "bodyBuffer";
return (req, res, next) => {
if (!skip?.(req, res)) {
const oldWrite = res.write
const oldEnd = res.end;
res.write = function () {
if (arguments[0]?.length > 0) {
if (!res[bufferName]) res[bufferName] = [];
res[bufferName].push(Buffer.from(arguments[0]));
}
return oldWrite.apply(res, arguments);
};
res.end = function () {
if (arguments[0]?.length > 0) {
if (!res[bufferName]) res[bufferName] = [];
res[bufferName].push(Buffer.from(arguments[0]));
}
return oldEnd.apply(res, arguments);
};
}
next();
}
}
/*
.tokenFunction
A default token function in following condition,
* response body buffer named "bodyBuffer"
* normal statusCode less than 400
* convert to text
* prifixed with line-break and "Res-body: "
* utf8
In any other condition, re-write your own token function.
*/
function tokenFunction(req, res) {
if (res.bodyBuffer && res.statusCode < 400) {
return "\nRes-body: " + Buffer.concat(res.bodyBuffer).toString('utf8');
}
}
//module exports
module.exports = {
createMiddleware,
tokenFunction,
};