-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathincoming.ts
More file actions
74 lines (62 loc) · 2.16 KB
/
incoming.ts
File metadata and controls
74 lines (62 loc) · 2.16 KB
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
/* !
* Tencent is pleased to support the open source community by making Tencent Server Web available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import * as http from "http";
// Max response body size
const maxBodySize = 512 * 1024;
export interface ResponseBodyInfo {
bodyLength: number;
bodyChunks: Buffer[];
body: Buffer;
bodyTooLarge: boolean;
}
export const captureReadableStream = (
stream: NodeJS.ReadableStream
): ResponseBodyInfo => {
const originPush = (stream as any).push;
const info: ResponseBodyInfo = {
bodyLength: 0,
bodyChunks: [],
bodyTooLarge: false,
body: Buffer.alloc(0)
};
Object.defineProperty(info, "body", {
// 需要用的时候才拼接buffer
get: () => Buffer.concat(info.bodyChunks)
});
const handler = (chunk: any): void => {
info.bodyLength += Buffer.byteLength(chunk);
// 到达最大限制后,不再记录回包内容
if (info.bodyTooLarge) {
return;
}
info.bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
info.bodyTooLarge = info.bodyLength > maxBodySize;
};
const rb = (stream as any).readableBuffer;
let { head } = rb;
if (head !== undefined) {
while (head) {
handler(head.data);
head = head.next;
}
} else if (rb.forEach) {
rb.forEach((c) => {
handler(c);
});
}
(stream as any).push = (chunk: any, encoding?: string): boolean => {
if (chunk) {
handler(chunk);
}
return originPush.call(stream, chunk, encoding);
};
return info;
};
export const captureIncoming = (
response: http.IncomingMessage
): ResponseBodyInfo => captureReadableStream(response);