-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.ts
51 lines (41 loc) · 1.29 KB
/
index.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
/// <reference types="vite/client" />
import viteDevServer from "vavite/http-dev-server";
import Fastify, { FastifyInstance } from "fastify";
import FastifyStatic from "@fastify/static";
import { renderPage } from "vike/server";
import { fileURLToPath } from "node:url";
import { IncomingMessage, ServerResponse } from "node:http";
async function startServer() {
const instance = Fastify({});
if (!viteDevServer) {
await instance.register(FastifyStatic, {
root: fileURLToPath(new URL("../client/assets", import.meta.url)),
prefix: "/assets/",
});
}
instance.get("*", async (request, reply) => {
const pageContext = await renderPage({ urlOriginal: request.url });
const { httpResponse } = pageContext;
if (!httpResponse) return;
const { body, statusCode, headers } = httpResponse;
headers.forEach(([name, value]) => reply.header(name, value));
reply.status(statusCode);
reply.send(body);
});
await instance.ready();
fastify = instance;
}
let fastify: FastifyInstance | undefined;
const fastifyHandlerPromise = startServer().catch((error) => {
console.error(error);
process.exit(1);
});
export default async function handler(
request: IncomingMessage,
reply: ServerResponse,
) {
if (!fastify) {
await fastifyHandlerPromise;
}
fastify!.server.emit("request", request, reply);
}