-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathentry-server.tsx
More file actions
72 lines (61 loc) · 1.93 KB
/
entry-server.tsx
File metadata and controls
72 lines (61 loc) · 1.93 KB
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
import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
import { ElementType } from "react";
import type { Context, RouteModule } from "@impalajs/core";
import { Writable, WritableOptions } from "node:stream";
import { HeadContext, HeadManager } from "./head-context";
class StringResponse extends Writable {
private buffer: string;
private responseData: Promise<string>;
constructor(options?: WritableOptions) {
super(options);
this.buffer = "";
this.responseData = new Promise((resolve, reject) => {
this.on("finish", () => resolve(this.buffer));
this.on("error", reject);
});
}
_write(
chunk: any,
encoding: BufferEncoding,
callback: (error?: Error | null) => void
): void {
this.buffer += chunk;
callback();
}
getData(): Promise<string> {
return this.responseData;
}
}
function HeadContent({ headManager }: { headManager: HeadManager }) {
return <>{...headManager.getHead()}</>;
}
export async function render(
context: Context,
mod: () => Promise<RouteModule<ElementType>>,
bootstrapModules?: Array<string>
) {
const { default: Page } = await mod();
// We create a new head manager for each request to avoid sharing state across routes
const headManager = new HeadManager();
const response = new StringResponse();
const { pipe } = renderToPipeableStream(
// Now on each render, each page will use their own head context instead of default one
(
<HeadContext.Provider value={headManager}>
<Page {...context} />
</HeadContext.Provider>
),
{
bootstrapModules,
bootstrapScriptContent: `window.___CONTEXT=${JSON.stringify(context)};`,
onAllReady() {
pipe(response);
},
onError(error) {
console.error(error);
},
});
const body = await response.getData();
const head = renderToStaticMarkup(<HeadContent headManager={headManager} />);
return { body, head };
}