-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathserver.ts
138 lines (119 loc) · 3.87 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
// IDK why this is needed when it's in the tsconfig..........
// YAY PROJECT REFERENCES!
/// <reference lib="DOM.Iterable" />
import type * as express from "express";
import type { AppLoadContext, ServerBuild } from "@remix-run/node";
import {
createRequestHandler as createRemixRequestHandler,
createReadableStreamFromReadable,
writeReadableStreamToWritable,
} from "@remix-run/node";
/**
* 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, such as
* values that are generated by Express middleware like `req.session`.
*/
export type GetLoadContextFunction = (
req: express.Request,
res: express.Response
) => Promise<AppLoadContext> | AppLoadContext;
export type RequestHandler = (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => Promise<void>;
/**
* Returns a request handler for Express that serves the response using Remix.
*/
export function createRequestHandler({
build,
getLoadContext,
mode = process.env.NODE_ENV,
}: {
build: ServerBuild | (() => Promise<ServerBuild>);
getLoadContext?: GetLoadContextFunction;
mode?: string;
}): RequestHandler {
let handleRequest = createRemixRequestHandler(build, mode);
return async (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
try {
let request = createRemixRequest(req, res);
let loadContext = await getLoadContext?.(req, res);
let response = await handleRequest(request, loadContext);
await sendRemixResponse(res, response);
} catch (error: unknown) {
// Express doesn't support async functions, so we have to pass along the
// error manually using next().
next(error);
}
};
}
export function createRemixHeaders(
requestHeaders: express.Request["headers"]
): Headers {
let headers = new Headers();
for (let [key, values] of Object.entries(requestHeaders)) {
if (values) {
if (Array.isArray(values)) {
for (let value of values) {
headers.append(key, value);
}
} else {
headers.set(key, values);
}
}
}
return headers;
}
export function createRemixRequest(
req: express.Request,
res: express.Response
): Request {
// req.hostname doesn't include port information so grab that from
// `X-Forwarded-Host` or `Host`
let [, hostnamePort] = req.get("X-Forwarded-Host")?.split(":") ?? [];
let [, hostPort] = req.get("host")?.split(":") ?? [];
let port = hostnamePort || hostPort;
// Use req.hostname here as it respects the "trust proxy" setting
let resolvedHost = `${req.hostname}${port ? `:${port}` : ""}`;
// Use `req.originalUrl` so Remix is aware of the full path
let url = new URL(`${req.protocol}://${resolvedHost}${req.originalUrl}`);
// Abort action/loaders once we can no longer write a response
let controller = new AbortController();
res.on("close", () => controller.abort());
let init: RequestInit = {
method: req.method,
headers: createRemixHeaders(req.headers),
signal: controller.signal,
};
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = createReadableStreamFromReadable(req);
(init as { duplex: "half" }).duplex = "half";
}
return new Request(url.href, init);
}
export async function sendRemixResponse(
res: express.Response,
nodeResponse: Response
): Promise<void> {
res.statusMessage = nodeResponse.statusText;
res.status(nodeResponse.status);
for (let [key, value] of nodeResponse.headers.entries()) {
res.append(key, value);
}
if (nodeResponse.headers.get("Content-Type")?.match(/text\/event-stream/i)) {
res.flushHeaders();
}
if (nodeResponse.body) {
await writeReadableStreamToWritable(nodeResponse.body, res);
} else {
res.end();
}
}