Repository navigation
Expand file tree
/
Copy pathdev-api.js
More file actions
83 lines (77 loc) · 2.24 KB
/
Copy pathdev-api.js
File metadata and controls
83 lines (77 loc) · 2.24 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
75
76
77
78
79
80
81
82
83
import { handleApiRequest } from "./api-router.js";
import { jsonResponse } from "./http.js";
async function readRequestBody(request) {
const chunks = [];
let bytes = 0;
for await (const chunk of request) {
const buffer = Buffer.from(chunk);
bytes += buffer.byteLength;
if (bytes > 32_000) throw new Error("REQUEST_TOO_LARGE");
chunks.push(buffer);
}
return Buffer.concat(chunks);
}
function requestHeaders(incoming) {
const headers = new Headers();
for (const [name, value] of Object.entries(incoming.headers)) {
if (Array.isArray(value)) {
for (const item of value) headers.append(name, item);
} else if (value !== undefined) {
headers.set(name, value);
}
}
return headers;
}
function configureLocalApi(server) {
server.middlewares.use(async (incoming, outgoing, next) => {
if (!incoming.url?.startsWith("/api/")) {
next();
return;
}
let response;
try {
const method = incoming.method ?? "GET";
const host = incoming.headers.host ?? "127.0.0.1";
const body = method === "GET" || method === "HEAD"
? undefined
: await readRequestBody(incoming);
const request = new Request(
new URL(incoming.url ?? "/", `http://${host}`),
{
method,
headers: requestHeaders(incoming),
body,
},
);
response = await handleApiRequest(request, process.env);
} catch (error) {
const tooLarge = error instanceof Error
&& error.message === "REQUEST_TOO_LARGE";
response = jsonResponse(
{
error: {
code: tooLarge ? "REQUEST_TOO_LARGE" : "INTERNAL_ERROR",
message: tooLarge ? "Request body is too large" : "SANDEVISTAN API failed",
},
},
{ status: tooLarge ? 413 : 500 },
);
}
if (!response) {
next();
return;
}
outgoing.statusCode = response.status;
response.headers.forEach((value, name) => {
outgoing.setHeader(name, value);
});
outgoing.end(Buffer.from(await response.arrayBuffer()));
});
}
export function sandevistanDevApi() {
return {
name: "sandevistan-dev-api",
configureServer: configureLocalApi,
configurePreviewServer: configureLocalApi,
};
}