-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.tsx
63 lines (49 loc) · 1.76 KB
/
server.tsx
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
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { type Context, createServer } from "ultra/server.ts";
import { createHeadInsertionTransformStream } from "ultra/stream.ts";
import { stringify, tw } from "./src/twind/twind.ts";
import App from "./src/app.tsx";
// React Router
import { StaticRouter } from "react-router-dom/server";
// React Query
import { QueryClientProvider } from "@tanstack/react-query";
import { useDehydrateReactQuery } from "./src/react-query/useDehydrateReactQuery.tsx";
import { queryClient } from "./src/react-query/query-client.ts";
const server = await createServer({
importMapPath: import.meta.resolve("./importMap.json"),
browserEntrypoint: import.meta.resolve("./client.tsx"),
});
function ServerApp({ context }: Context) {
useDehydrateReactQuery(queryClient);
const requestUrl = new URL(context.req.url);
return (
<QueryClientProvider client={queryClient}>
<StaticRouter location={new URL(context.req.url).pathname}>
<App />
</StaticRouter>
</QueryClientProvider>
);
}
server.get("*", async (context) => {
// clear query cache
queryClient.clear();
/**
* Render the request
*/
const result = await server.render(<ServerApp context={context} />);
// Inject the style tag into the head of the streamed response
const stylesInject = createHeadInsertionTransformStream(() => {
if (Array.isArray(tw.target)) {
return Promise.resolve(stringify(tw.target));
}
throw new Error("Expected tw.target to be an instance of an Array");
});
const transformed = result.pipeThrough(stylesInject);
return context.body(transformed, 200, {
"content-type": "text/html; charset=utf-8",
});
});
if (import.meta.main) {
serve(server.fetch);
}
export default server;