forked from BSteffaniak/serverless_oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
88 lines (79 loc) · 2.51 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
80
81
82
83
84
85
86
87
88
import type {
APIGatewayProxyEvent,
APIGatewayProxyEventV2,
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";
export const serverRequest = (
event: APIGatewayProxyEvent | APIGatewayProxyEventV2,
context: Context
): Request => {
const headers = new Headers(event.headers as unknown as string[][] ?? undefined);
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));
const url = new URL(`https://${event.requestContext.domainName}`);
const init: RequestInit = {
headers: headers,
body: body,
};
if ("rawPath" in event) {
url.pathname = event.rawPath;
init.method = event.requestContext.http.method;
} else if ("path" in event) {
url.pathname = event.path;
init.method = event.httpMethod;
} else {
throw new Error("Unsupported APIGatewayProxyEvent version")
}
if (event.queryStringParameters) {
for (const i of Object.keys(event.queryStringParameters)) {
url.searchParams.append(i, event.queryStringParameters[i]!);
}
}
return new Request(url, init);
};
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 | APIGatewayProxyEventV2,
context: Context,
app: Application
) => {
const request = serverRequest(event, context);
const response = await app.handle(request);
return apiGatewayResponse(response);
};