-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhandler.ts
56 lines (47 loc) · 1.33 KB
/
handler.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
/// <reference types="vite/client" />
import Fastify, { RouteHandlerMethod } from "fastify";
import viteDevServer from "vavite/vite-dev-server";
import { IncomingMessage, ServerResponse } from "node:http";
const fastify = Fastify({
// Your Fastify options go here.
});
// This is an optional optimization to load routes lazily so that
// when reloadOn option is set to "static-deps-change",
// changes to the route handlers will not trigger a reload.
// Feel free to remove this and import routes directly.
function lazy(
importer: () => Promise<{ default: RouteHandlerMethod }>,
): RouteHandlerMethod {
return async (req, res) => {
try {
const routeHandler = (await importer()).default;
return routeHandler.bind(fastify)(req, res);
} catch (err) {
if (err instanceof Error) viteDevServer?.ssrFixStacktrace(err);
throw err;
}
};
}
fastify.get(
"/",
lazy(() => import("./routes/home")),
);
fastify.get(
"/foo",
lazy(() => import("./routes/foo")),
);
fastify.get(
"/bar",
lazy(() => import("./routes/bar")),
);
let fastifyReadyPromise: PromiseLike<void> | undefined = fastify.ready();
export default async function handler(
request: IncomingMessage,
reply: ServerResponse,
) {
if (fastifyReadyPromise) {
await fastifyReadyPromise;
fastifyReadyPromise = undefined;
}
fastify.server.emit("request", request, reply);
}