-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
server.ts
144 lines (125 loc) · 4.04 KB
/
server.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import type {
AppLoadContext,
ServerBuild,
RequestInit as NodeRequestInit,
Response as NodeResponse,
} from "@remix-run/node";
import {
AbortController as NodeAbortController,
Headers as NodeHeaders,
Request as NodeRequest,
createRequestHandler as createRemixRequestHandler,
readableStreamToString,
} from "@remix-run/node";
import type {
APIGatewayProxyEventHeaders,
APIGatewayProxyEventV2,
APIGatewayProxyHandlerV2,
APIGatewayProxyStructuredResultV2,
} from "aws-lambda";
import { isBinaryType } from "./binaryTypes";
/**
* A function that returns the value to use as `context` in route `loader` and
* `action` functions.
*
* You can think of this as an escape hatch that allows you to pass
* environment/platform-specific values through to your loader/action.
*/
export type GetLoadContextFunction = (
event: APIGatewayProxyEventV2
) => AppLoadContext;
export type RequestHandler = APIGatewayProxyHandlerV2;
/**
* Returns a request handler for Architect that serves the response using
* Remix.
*/
export function createRequestHandler({
build,
getLoadContext,
mode = process.env.NODE_ENV,
}: {
build: ServerBuild;
getLoadContext?: GetLoadContextFunction;
mode?: string;
}): RequestHandler {
let handleRequest = createRemixRequestHandler(build, mode);
return async (event) => {
let request = createRemixRequest(event);
let loadContext = getLoadContext?.(event);
let response = (await handleRequest(request, loadContext)) as NodeResponse;
return sendRemixResponse(response);
};
}
export function createRemixRequest(event: APIGatewayProxyEventV2): NodeRequest {
let host = event.headers["x-forwarded-host"] || event.headers.host;
let search = event.rawQueryString.length ? `?${event.rawQueryString}` : "";
let scheme = process.env.ARC_SANDBOX ? "http" : "https";
let url = new URL(`${scheme}://${host}${event.rawPath}${search}`);
let isFormData = event.headers["content-type"]?.includes(
"multipart/form-data"
);
// Note: No current way to abort these for Architect, but our router expects
// requests to contain a signal so it can detect aborted requests
let controller = new NodeAbortController();
return new NodeRequest(url.href, {
method: event.requestContext.http.method,
headers: createRemixHeaders(event.headers, event.cookies),
// Cast until reason/throwIfAborted added
// https://github.com/mysticatea/abort-controller/issues/36
signal: controller.signal as NodeRequestInit["signal"],
body:
event.body && event.isBase64Encoded
? isFormData
? Buffer.from(event.body, "base64")
: Buffer.from(event.body, "base64").toString()
: event.body,
});
}
export function createRemixHeaders(
requestHeaders: APIGatewayProxyEventHeaders,
requestCookies?: string[]
): NodeHeaders {
let headers = new NodeHeaders();
for (let [header, value] of Object.entries(requestHeaders)) {
if (value) {
headers.append(header, value);
}
}
if (requestCookies) {
headers.append("Cookie", requestCookies.join("; "));
}
return headers;
}
export async function sendRemixResponse(
nodeResponse: NodeResponse
): Promise<APIGatewayProxyStructuredResultV2> {
let cookies: string[] = [];
// Arc/AWS API Gateway will send back set-cookies outside of response headers.
for (let [key, values] of Object.entries(nodeResponse.headers.raw())) {
if (key.toLowerCase() === "set-cookie") {
for (let value of values) {
cookies.push(value);
}
}
}
if (cookies.length) {
nodeResponse.headers.delete("Set-Cookie");
}
let contentType = nodeResponse.headers.get("Content-Type");
let isBase64Encoded = isBinaryType(contentType);
let body: string | undefined;
if (nodeResponse.body) {
if (isBase64Encoded) {
body = await readableStreamToString(nodeResponse.body, "base64");
} else {
body = await nodeResponse.text();
}
}
return {
statusCode: nodeResponse.status,
headers: Object.fromEntries(nodeResponse.headers.entries()),
cookies,
body,
isBase64Encoded,
};
}