-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
response.ts
72 lines (63 loc) · 1.88 KB
/
response.ts
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
import { streamAsyncIterator } from './util.js';
const isNodeJS =
typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]';
let StreamingCompatibleResponse: typeof Response | undefined;
function createResponseClass() {
StreamingCompatibleResponse = class extends Response {
#isStream: boolean;
#body: any;
constructor(body?: BodyInit | null, init?: ResponseInit) {
let isStream = body instanceof ReadableStream;
super(isStream ? null : body, init);
this.#isStream = isStream;
this.#body = body;
}
get body() {
return this.#body;
}
async text(): Promise<string> {
if (this.#isStream && isNodeJS) {
let decoder = new TextDecoder();
let body = this.#body;
let out = '';
for await (let chunk of streamAsyncIterator(body)) {
out += decoder.decode(chunk);
}
return out;
}
return super.text();
}
async arrayBuffer(): Promise<ArrayBuffer> {
if (this.#isStream && isNodeJS) {
let body = this.#body;
let chunks: Uint8Array[] = [];
let len = 0;
for await (let chunk of streamAsyncIterator(body)) {
chunks.push(chunk);
len += chunk.length;
}
let ab = new Uint8Array(len);
let offset = 0;
for (const chunk of chunks) {
ab.set(chunk, offset);
offset += chunk.length;
}
return ab;
}
return super.arrayBuffer();
}
};
return StreamingCompatibleResponse;
}
type CreateResponseFn = (body?: BodyInit | null, init?: ResponseInit) => Response;
export const createResponse: CreateResponseFn = isNodeJS
? (body, init) => {
if (typeof body === 'string' || ArrayBuffer.isView(body)) {
return new Response(body, init);
}
if (typeof StreamingCompatibleResponse === 'undefined') {
return new (createResponseClass())(body, init);
}
return new StreamingCompatibleResponse(body, init);
}
: (body, init) => new Response(body, init);