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

index.mjs

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