-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentry.ts
More file actions
75 lines (66 loc) · 1.94 KB
/
entry.ts
File metadata and controls
75 lines (66 loc) · 1.94 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
import type {
CloudFrontHeaders,
Context,
CloudFrontRequestEvent,
CloudFrontResultResponse,
} from "aws-lambda";
import "#internal/nitro/virtual/polyfill";
const nitroApp = useNitroApp();
export const handler = async function handler(
event: CloudFrontRequestEvent,
context: Context
): Promise<CloudFrontResultResponse> {
const request = event.Records[0].cf.request;
const url = getFullUrl(request.uri, request.querystring);
const r = await nitroApp.localCall({
event,
url,
context,
headers: normalizeIncomingHeaders(request.headers),
method: request.method,
query: request.querystring,
body: normalizeBody(request.body),
});
return {
status: r.status.toString(),
headers: normalizeOutgoingHeaders(r.headers),
body: r.body.toString(),
};
};
function normalizeBody(
body: CloudFrontRequestEvent["Records"][0]["cf"]["request"]["body"]
) {
if (typeof body === "undefined") {
return body;
}
const bodyString = body;
if (typeof body.encoding !== "undefined" && body.encoding === "base64") {
bodyString.data = Buffer.from(body.data, "base64").toString("utf8");
bodyString.data = decodeURIComponent(bodyString.data);
}
return bodyString;
}
function normalizeIncomingHeaders(headers: CloudFrontHeaders) {
return Object.fromEntries(
Object.entries(headers).map(([key, keyValues]) => [
key,
keyValues.map((kv) => kv.value),
])
);
}
function normalizeOutgoingHeaders(
headers: Record<string, string | string[] | undefined>
): CloudFrontHeaders {
const entries = Object.fromEntries(
Object.entries(headers).filter(([key]) => !["content-length"].includes(key))
);
return Object.fromEntries(
Object.entries(entries).map(([k, v]) => [
k,
Array.isArray(v) ? v.map((value) => ({ value })) : [{ value: v || '' }],
])
);
}
function getFullUrl(uri: string, querystring: string | undefined) {
return uri + (querystring ? "?" + querystring : "");
}