Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.mjs

306 lines7.3 KB

1import { createServer } from 'node:http'
2import { readFile } from 'node:fs/promises'
3import { dirname, extname, resolve, sep } from 'node:path'
4import { setTimeout as sleep } from 'node:timers/promises'
5import { fileURLToPath } from 'node:url'
6import { render } from '@lit-labs/ssr'
7import { collectResult } from '@lit-labs/ssr/lib/render-result.js'
8import { html } from 'lit'
9import { QueryClient, dehydrate } from '@tanstack/lit-query'
10import {
11 SSR_BASE_URL,
12 SSR_HOST,
13 SSR_PORT,
14 SSR_PUBLIC_ORIGIN,
15} from '../config/ports.js'
16import {
17 DEFAULT_MESSAGE,
18 QUERY_STALE_TIME,
19 createDataQueryOptions,
20} from '../src/api.js'
21import {
22 getSsrQueryControllerCreationCount,
23 resetSsrQueryControllerCreationCount,
24} from '../src/app.ts'
25​
26const serverDir = dirname(fileURLToPath(import.meta.url))
27const distDir = resolve(serverDir, '../dist')
28const templatePath = resolve(distDir, 'index.html')
29​
30const contentTypes = {
31 '.css': 'text/css; charset=utf-8',
32 '.js': 'text/javascript; charset=utf-8',
33 '.json': 'application/json; charset=utf-8',
34 '.svg': 'image/svg+xml; charset=utf-8',
36​
37let requestCount = 0
38let failNextDataRequest = false
39let nextDataDelayMs = 0
40​
41const apiCorsHeaders = {
42 'access-control-allow-headers': 'content-type',
43 'access-control-allow-methods': 'GET,POST,OPTIONS',
44 'access-control-allow-origin': '*',
46​
47function createBrowserQueryClient() {
48 return new QueryClient({
49 defaultOptions: {
50 queries: {
51 retry: false,
52 staleTime: QUERY_STALE_TIME,
53 },
54 },
55 })
57​
58function nextDataResponse() {
59 requestCount += 1
60 return {
61 message: DEFAULT_MESSAGE,
62 requestCount,
63 servedAt: new Date().toISOString(),
64 }
66​
67function resetApiState() {
68 requestCount = 0
69 failNextDataRequest = false
70 nextDataDelayMs = 0
72​
73function parseNonNegativeDelayMs(value) {
74 const parsedDelayMs = Number.parseInt(value ?? '', 10)
75 if (!Number.isInteger(parsedDelayMs) || parsedDelayMs < 0) {
76 return undefined
77 }
78​
79 return parsedDelayMs
81​
82async function consumeNextDataDelay() {
83 const delayMs = nextDataDelayMs
84 nextDataDelayMs = 0
85​
86 if (delayMs > 0) {
87 await sleep(delayMs)
88 }
90​
91function consumeFailNextDataRequest() {
92 if (!failNextDataRequest) {
93 return false
94 }
95​
96 failNextDataRequest = false
97 return true
99​
100function writeBuffer(res, statusCode, contentType, payload, extraHeaders = {}) {
101 res.writeHead(statusCode, {
102 'cache-control': 'no-store',
103 'content-length': payload.byteLength,
104 'content-type': contentType,
105 ...extraHeaders,
106 })
107 res.end(payload)
109​
110function writeHtml(res, statusCode, body, extraHeaders = {}) {
111 const payload = Buffer.from(body)
112 writeBuffer(
113 res,
114 statusCode,
115 'text/html; charset=utf-8',
116 payload,
117 extraHeaders,
118 )
120​
121function writeJson(res, statusCode, body) {
122 const payload = Buffer.from(JSON.stringify(body))
123 writeBuffer(
124 res,
125 statusCode,
126 'application/json; charset=utf-8',
127 payload,
128 apiCorsHeaders,
129 )
131​
132function serializeJsonForHtml(value) {
133 return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (character) => {
134 switch (character) {
135 case '<':
136 return '\\u003c'
137 case '>':
138 return '\\u003e'
139 case '&':
140 return '\\u0026'
141 case '\u2028':
142 return '\\u2028'
143 case '\u2029':
144 return '\\u2029'
145 default:
146 return character
147 }
148 })
150​
151async function readTemplate() {
152 try {
153 return await readFile(templatePath, 'utf8')
154 } catch (error) {
155 if (error && typeof error === 'object' && 'code' in error) {
156 throw new Error(
157 'Missing built client assets. Run "pnpm --dir examples/lit/ssr run build" from the repo root first.',
158 )
159 }
160​
161 throw error
162 }
164​
165async function serveAsset(pathname, res) {
166 if (!pathname.startsWith('/assets/')) {
167 return false
168 }
169​
170 const assetPath = resolve(distDir, `.${pathname}`)
171 const distRootPrefix = `${distDir}${sep}`
172 if (!assetPath.startsWith(distRootPrefix)) {
173 return false
174 }
175​
176 try {
177 const file = await readFile(assetPath)
178 const contentType =
179 contentTypes[extname(assetPath)] ?? 'application/octet-stream'
180 writeBuffer(res, 200, contentType, file)
181 return true
182 } catch {
183 return false
184 }
186​
187async function renderPage(res) {
188 const queryClient = createBrowserQueryClient()
189 resetSsrQueryControllerCreationCount(queryClient)
190 const dataQueryOptions = createDataQueryOptions(SSR_PUBLIC_ORIGIN)
191 await queryClient.query(dataQueryOptions).catch((error) => {
192 throw new Error(
193 'SSR prefetch did not complete successfully. Refusing to render loading HTML.',
194 { cause: error },
195 )
196 })
197​
198 const appHtml = await collectResult(
199 render(
200 html`<ssr-app
201 api-base-url=${SSR_PUBLIC_ORIGIN}
202 .queryClient=${queryClient}
203 ></ssr-app>`,
204 ),
205 )
206​
207 const dehydratedState = dehydrate(queryClient)
208 const controllerCreationCount =
209 getSsrQueryControllerCreationCount(queryClient)
210 if (controllerCreationCount < 1) {
211 throw new Error('SSR render did not exercise createQueryController.')
212 }
213​
214 const template = await readTemplate()
215 const htmlDocument = template
216 .replace('__SSR_APP_HTML__', appHtml)
217 .replace('__QUERY_STATE_JSON__', serializeJsonForHtml(dehydratedState))
218​
219 writeHtml(res, 200, htmlDocument, {
220 'x-ssr-query-controller-created': String(controllerCreationCount),
221 })
223​
224const server = createServer(async (req, res) => {
225 const requestUrl = new URL(req.url ?? '/', SSR_BASE_URL)
226 const method = req.method ?? 'GET'
227​
228 if (method === 'OPTIONS' && requestUrl.pathname.startsWith('/api/')) {
229 res.writeHead(204, {
230 'cache-control': 'no-store',
231 ...apiCorsHeaders,
232 })
233 res.end()
234 return
235 }
236​
237 if (method === 'GET' && requestUrl.pathname === '/api/data') {
238 await consumeNextDataDelay()
239​
240 if (consumeFailNextDataRequest()) {
241 writeJson(res, 500, { error: 'Forced data failure (test)' })
242 return
243 }
244​
245 writeJson(res, 200, nextDataResponse())
246 return
247 }
248​
249 if (method === 'GET' && requestUrl.pathname === '/api/request-count') {
250 writeJson(res, 200, { count: requestCount })
251 return
252 }
253​
254 if (method === 'POST' && requestUrl.pathname === '/api/reset') {
255 resetApiState()
256 writeJson(res, 200, { ok: true })
257 return
258 }
259​
260 if (method === 'POST' && requestUrl.pathname === '/api/test/fail-next-data') {
261 failNextDataRequest = true
262 writeJson(res, 200, { ok: true })
263 return
264 }
265​
266 if (
267 method === 'POST' &&
268 requestUrl.pathname === '/api/test/delay-next-data'
269 ) {
270 const delayMs = parseNonNegativeDelayMs(requestUrl.searchParams.get('ms'))
271 if (delayMs === undefined) {
272 writeJson(res, 400, { error: 'Invalid ms query parameter.' })
273 return
274 }
275​
276 nextDataDelayMs = delayMs
277 writeJson(res, 200, { ok: true, delayMs })
278 return
279 }
280​
281 if (method === 'GET' && requestUrl.pathname === '/') {
282 try {
283 await renderPage(res)
284 } catch (error) {
285 console.error('[ssr] render failed:', error)
286 writeHtml(
287 res,
288 500,
289 '<!doctype html><html><body>SSR render failed.</body></html>',
290 )
291 }
292 return
293 }
294​
295 if (method === 'GET' && (await serveAsset(requestUrl.pathname, res))) {
296 return
297 }
298​
299 writeJson(res, 404, { error: 'Not found' })
300})
301​
302server.listen(SSR_PORT, SSR_HOST, () => {
303 console.log(
304 `[ssr] listening on ${SSR_BASE_URL} (public origin ${SSR_PUBLIC_ORIGIN})`,
305 )
306})