-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod.ts
79 lines (72 loc) · 2.2 KB
/
mod.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
73
74
75
76
77
78
79
import type {
APIGatewayProxyEvent,
Application,
Context
} from "./deps.ts";
// deno-lint-ignore no-explicit-any
const isReader = (value: any): value is Deno.Reader =>
value &&
typeof value === "object" &&
"read" in value &&
typeof value.read === "function";
const eventUrl = (event: APIGatewayProxyEvent): string => {
if (event.queryStringParameters) {
return `${event.path}?${Object.keys(event.queryStringParameters)
.map((k) => `${k}=${event.queryStringParameters![k]}`)
.join("&")}`;
}
return event.path;
};
export const serverRequest = (
event: APIGatewayProxyEvent,
context: Context
): Request => {
const headers = new Headers(event.headers as unknown as string[][] ?? undefined);
const url = eventUrl(event);
const body = event.body ? new TextEncoder().encode(event.body) : undefined;
if (body && !headers.get("Content-Length")) {
headers.set("Content-Length", body.length.toString());
}
const clonedEvent = JSON.parse(JSON.stringify(event));
delete clonedEvent.body;
headers.set("x-apigateway-event", JSON.stringify(clonedEvent));
headers.set("x-apigateway-context", JSON.stringify(context));
return new Request(url, {
method: event.httpMethod,
headers: headers,
body,
});
};
export const apiGatewayResponse = async (response?: Response) => {
if (!response) {
return { statusCode: 500 };
}
if (!response.body) {
return { statusCode: response.status };
}
let arrayBuf;
if (isReader(response.body)) {
const buf = new Uint8Array(1024);
const n = (await response.body.read(buf))!;
arrayBuf = buf.subarray(0, n);
} else {
const result = await response.body.getReader().read();
arrayBuf = result.value;
}
const rawHeaders: { [key: string]: string } = {};
response.headers.forEach((value: string, key: string) => (rawHeaders[key] = value));
return {
statusCode: response.status,
body: new TextDecoder().decode(arrayBuf).trim(),
headers: rawHeaders,
};
};
export const handler = async (
event: APIGatewayProxyEvent,
context: Context,
app: Application
) => {
const request = serverRequest(event, context);
const response = await app.handle(request);
return apiGatewayResponse(response);
};