-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (63 loc) · 2.12 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
module.exports = function expressModifyResponse(checkCallback, modifyCallback)
{
return function expressModifyResponse(req, res, next) {
var _end = res.end;
var _write = res.write;
var checked = false;
var buffers = [];
var addBuffer = (chunk, encoding) => {
if (chunk === undefined) return;
if (typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
buffers.push(chunk);
};
res.write = function write(chunk, encoding) {
if (!checked) {
checked = true;
var hook = checkCallback(req, res);
if (!hook) {
res.end = _end;
res.write = _write;
return res.write(chunk, encoding);
} else {
addBuffer(chunk, encoding);
}
} else {
addBuffer(chunk, encoding);
}
};
res.end = function end(chunk, encoding) {
if (!checked) {
checked = true;
var hook = checkCallback(req, res);
if (!hook) {
res.end = _end;
res.write = _write;
return res.end(chunk, encoding);
} else {
addBuffer(chunk, encoding);
}
} else {
addBuffer(chunk, encoding);
}
var buffer = Buffer.concat(buffers);
Promise.resolve(modifyCallback(req, res, buffer)).then((result) => {
if (typeof result === 'string') {
result = new Buffer(result, 'utf-8');
}
if (res.getHeader('Content-Length')) {
res.setHeader('Content-Length', String(result.length));
}
res.end = _end;
res.write = _write;
res.write(result);
res.end();
}).catch((e) => {
// handle?
next(e);
});
};
next();
};
}