forked from kitajs/html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
suspense-server.tsx
87 lines (72 loc) · 2.18 KB
/
suspense-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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import http from 'http';
import { setTimeout } from 'timers/promises';
import Html from '../index';
import { Suspense, renderToStream } from '../suspense';
async function WaitFor({ s }: { s: number }) {
await setTimeout(Number(s) * 1000);
return <div>Loaded after: {s}s</div>;
}
function renderLayout(rid: number) {
return (
<html>
<body>
<div>Hello</div>
<Suspense rid={rid} fallback={<div>loading 2s</div>}>
<div style="color: red">
<WaitFor s={1} />
</div>
<div style="color: red">
<WaitFor s={1} />
</div>
</Suspense>
<div>World</div>
<Suspense rid={rid} fallback={<div>loading 3s</div>}>
<div style="color: green">
<WaitFor s={3} />
</div>
<div style="color: green">
<WaitFor s={3} />
</div>
</Suspense>
<div>World</div>
<Suspense rid={rid} fallback={<div>loading 2s</div>}>
<div style="color: blue">
<WaitFor s={2} />
</div>
<div style="color: blue">
<WaitFor s={2} />
</div>
</Suspense>
<div>World</div>
<Suspense rid={rid} fallback={<div>loading random</div>}>
<div style="color: green">
<WaitFor s={3} />
</div>
<div style="color: green">
<WaitFor s={4.5} />
</div>
</Suspense>
<div>World</div>
</body>
</html>
);
}
http
.createServer((req, response) => {
// This simple webserver only has a index.html file
if (req.url !== '/' && req.url !== '/index.html') {
response.end();
return;
}
// ⚠️ Charset utf8 is important to avoid old browsers utf7 xss attacks
response.setHeader('Content-Type', 'text/html; charset=utf-8');
// Creates the html stream
const htmlStream = renderToStream(renderLayout);
// Pipes it into the response
htmlStream.pipe(response);
// If its an express or fastify server, just use
// response.type('text/html; charset=utf-8').send(htmlStream);
})
.listen(8080, () => {
console.log('Listening to http://localhost:8080');
});