Repository navigation
Expand file tree
/
Copy pathhttp.js
More file actions
55 lines (50 loc) · 1.61 KB
/
Copy pathhttp.js
File metadata and controls
55 lines (50 loc) · 1.61 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
702F
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
export function jsonResponse(body, init = {}) {
const headers = new Headers(init.headers);
headers.set("content-type", "application/json; charset=utf-8");
headers.set("x-content-type-options", "nosniff");
return new Response(JSON.stringify(body), { ...init, headers });
}
export async function readLimitedBytes(response, maxBytes) {
const reader = response.body?.getReader();
if (!reader) return new Uint8Array();
const chunks = [];
let size = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > maxBytes) {
await reader.cancel();
throw new Error("RESPONSE_TOO_LARGE");
}
chunks.push(value);
}
const output = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.byteLength;
}
return output;
}
export async function readLimitedRequestJson(request, maxBytes) {
const declared = Number(request.headers.get("content-length") ?? 0);
if (Number.isFinite(declared) && declared > maxBytes) {
throw new Error("REQUEST_TOO_LARGE");
}
const bytes = new Uint8Array(await request.arrayBuffer());
if (bytes.byteLength > maxBytes) throw new Error("REQUEST_TOO_LARGE");
return JSON.parse(new TextDecoder().decode(bytes));
}
export function createTimeout(
milliseconds,
setTimeoutImpl = setTimeout,
clearTimeoutImpl = clearTimeout,
) {
const controller = new AbortController();
const timer = setTimeoutImpl(() => controller.abort(), milliseconds);
return {
signal: controller.signal,
dispose: () => clearTimeoutImpl(timer),
};
}