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

index.mjs

340 lines7.8 KB

1import { createServer } from 'node:http'
2import { API_PORT } from '../config/ports.js'
3​
4const PAGE_SIZE = 10
5const TOTAL_PROJECTS = 50
6const JSON_CONTENT_TYPE = 'application/json'
7​
8function createSeedProjects() {
9 return Array.from({ length: TOTAL_PROJECTS }, (_, index) => ({
10 id: index + 1,
11 name: `Project ${index + 1}`,
12 owner: `Team ${(index % 5) + 1}`,
13 isFavorite: false,
14 }))
16​
17let projects = createSeedProjects()
18let nextProjectId = projects.length + 1
19let totalRequestCount = 0
20let totalMutationCount = 0
21let failNextMutation = false
22const perPageRequestCount = new Map()
23​
24function writeJson(res, status, body) {
25 const payload = JSON.stringify(body)
26 res.writeHead(status, {
27 'content-type': 'application/json; charset=utf-8',
28 'cache-control': 'no-store',
29 'access-control-allow-origin': '*',
30 'access-control-allow-methods': 'GET,POST,PATCH,OPTIONS',
31 'access-control-allow-headers': 'content-type',
32 'content-length': Buffer.byteLength(payload),
33 })
34 res.end(payload)
36​
37function parsePositiveInt(rawValue, fallback) {
38 if (rawValue == null || rawValue === '') {
39 return fallback
40 }
41​
42 const parsed = Number.parseInt(rawValue, 10)
43 if (!Number.isInteger(parsed) || parsed < 1) {
44 return undefined
45 }
46​
47 return parsed
49​
50function parseNonNegativeInt(rawValue, fallback) {
51 if (rawValue == null || rawValue === '') {
52 return fallback
53 }
54​
55 const parsed = Number.parseInt(rawValue, 10)
56 if (!Number.isInteger(parsed) || parsed < 0) {
57 return undefined
58 }
59​
60 return parsed
62​
63function resetState() {
64 projects = createSeedProjects()
65 nextProjectId = projects.length + 1
66 totalRequestCount = 0
67 totalMutationCount = 0
68 failNextMutation = false
69 perPageRequestCount.clear()
71​
72async function sleep(ms) {
73 if (!ms || ms <= 0) {
74 return
75 }
76​
77 await new Promise((resolve) => {
78 setTimeout(resolve, ms)
79 })
81​
82async function readJsonBody(req) {
83 const contentType = req.headers['content-type']
84 if (!contentType || !contentType.startsWith(JSON_CONTENT_TYPE)) {
85 return {
86 ok: false,
87 status: 415,
88 error: 'Expected application/json request body',
89 }
90 }
91​
92 const chunks = []
93 for await (const chunk of req) {
94 chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
95 }
96​
97 const raw = Buffer.concat(chunks).toString('utf8')
98 if (!raw) {
99 return {
100 ok: false,
101 status: 400,
102 error: 'Request body is required',
103 }
104 }
105​
106 try {
107 return {
108 ok: true,
109 value: JSON.parse(raw),
110 }
111 } catch {
112 return {
113 ok: false,
114 status: 400,
115 error: 'Request body must be valid JSON',
116 }
117 }
119​
120function buildProjectsPage(page) {
121 const totalPages = Math.max(1, Math.ceil(projects.length / PAGE_SIZE))
122 const boundedPage = Math.min(page, totalPages)
123 const startIndex = (boundedPage - 1) * PAGE_SIZE
124 const endIndex = startIndex + PAGE_SIZE
125 const items = projects.slice(startIndex, endIndex)
126​
127 totalRequestCount += 1
128 const pageRequests = (perPageRequestCount.get(boundedPage) ?? 0) + 1
129 perPageRequestCount.set(boundedPage, pageRequests)
130​
131 return {
132 page: boundedPage,
133 pageSize: PAGE_SIZE,
134 totalPages,
135 totalProjects: projects.length,
136 hasMore: boundedPage < totalPages,
137 projects: items,
138 requestMeta: {
139 totalRequestCount,
140 pageRequestCount: pageRequests,
141 totalMutationCount,
142 },
143 }
145​
146function maybeFailMutation(res) {
147 if (!failNextMutation) {
148 return false
149 }
150​
151 failNextMutation = false
152 writeJson(res, 500, { error: 'Forced mutation failure (test)' })
153 return true
155​
156function validateProjectName(name) {
157 if (typeof name !== 'string') {
158 return 'Project name must be a string'
159 }
160​
161 const trimmed = name.trim()
162 if (trimmed.length < 3) {
163 return 'Project name must be at least 3 characters'
164 }
165​
166 if (trimmed.length > 60) {
167 return 'Project name must be 60 characters or fewer'
168 }
169​
170 return null
172​
173function validateOwner(owner) {
174 if (typeof owner !== 'string') {
175 return 'Owner must be a string'
176 }
177​
178 const trimmed = owner.trim()
179 if (!trimmed) {
180 return 'Owner is required'
181 }
182​
183 if (trimmed.length > 40) {
184 return 'Owner must be 40 characters or fewer'
185 }
186​
187 return null
189​
190const server = createServer(async (req, res) => {
191 if (req.method === 'OPTIONS') {
192 res.writeHead(204, {
193 'access-control-allow-origin': '*',
194 'access-control-allow-methods': 'GET,POST,PATCH,OPTIONS',
195 'access-control-allow-headers': 'content-type',
196 'cache-control': 'no-store',
197 })
198 res.end()
199 return
200 }
201​
202 if (!req.url) {
203 writeJson(res, 400, { error: 'Missing URL' })
204 return
205 }
206​
207 const requestUrl = new URL(req.url, `http://127.0.0.1:${API_PORT}`)
208​
209 if (requestUrl.pathname === '/api/projects' && req.method === 'GET') {
210 const page = parsePositiveInt(requestUrl.searchParams.get('page'), 1)
211 if (!page) {
212 writeJson(res, 400, { error: 'Invalid page parameter' })
213 return
214 }
215​
216 const delayMs = parseNonNegativeInt(requestUrl.searchParams.get('delay'), 0)
217 if (delayMs === undefined) {
218 writeJson(res, 400, { error: 'Invalid delay parameter' })
219 return
220 }
221​
222 await sleep(delayMs)
223​
224 if (requestUrl.searchParams.get('error') === 'true') {
225 writeJson(res, 500, {
226 error: 'Forced server error (test)',
227 page,
228 })
229 return
230 }
231​
232 writeJson(res, 200, buildProjectsPage(page))
233 return
234 }
235​
236 if (requestUrl.pathname === '/api/projects' && req.method === 'POST') {
237 if (maybeFailMutation(res)) {
238 return
239 }
240​
241 const payload = await readJsonBody(req)
242 if (!payload.ok) {
243 writeJson(res, payload.status, { error: payload.error })
244 return
245 }
246​
247 const nameError = validateProjectName(payload.value?.name)
248 if (nameError) {
249 writeJson(res, 422, { error: nameError })
250 return
251 }
252​
253 const ownerError = validateOwner(payload.value?.owner)
254 if (ownerError) {
255 writeJson(res, 422, { error: ownerError })
256 return
257 }
258​
259 const project = {
260 id: nextProjectId,
261 name: payload.value.name.trim(),
262 owner: payload.value.owner.trim(),
263 isFavorite: false,
264 }
265​
266 nextProjectId += 1
267 totalMutationCount += 1
268 projects = [project, ...projects]
269​
270 writeJson(res, 201, {
271 project,
272 mutationCount: totalMutationCount,
273 })
274 return
275 }
276​
277 const patchMatch = requestUrl.pathname.match(/^\/api\/projects\/(\d+)$/)
278 if (patchMatch && req.method === 'PATCH') {
279 if (maybeFailMutation(res)) {
280 return
281 }
282​
283 const projectId = Number.parseInt(patchMatch[1], 10)
284 const projectIndex = projects.findIndex(
285 (project) => project.id === projectId,
286 )
287 if (projectIndex === -1) {
288 writeJson(res, 404, { error: `Project ${projectId} was not found` })
289 return
290 }
291​
292 const payload = await readJsonBody(req)
293 if (!payload.ok) {
294 writeJson(res, payload.status, { error: payload.error })
295 return
296 }
297​
298 if (typeof payload.value?.isFavorite !== 'boolean') {
299 writeJson(res, 422, { error: 'isFavorite must be a boolean' })
300 return
301 }
302​
303 const nextProject = {
304 ...projects[projectIndex],
305 isFavorite: payload.value.isFavorite,
306 }
307​
308 totalMutationCount += 1
309 projects = projects.map((project, index) =>
310 index === projectIndex ? nextProject : project,
311 )
312​
313 writeJson(res, 200, {
314 project: nextProject,
315 mutationCount: totalMutationCount,
316 })
317 return
318 }
319​
320 if (
321 requestUrl.pathname === '/api/testing/fail-next-mutation' &&
322 req.method === 'POST'
323 ) {
324 failNextMutation = true
325 writeJson(res, 200, { ok: true })
326 return
327 }
328​
329 if (requestUrl.pathname === '/api/reset' && req.method === 'POST') {
330 resetState()
331 writeJson(res, 200, { ok: true })
332 return
333 }
334​
335 writeJson(res, 404, { error: 'Not found' })
336})
337​
338server.listen(API_PORT, '127.0.0.1', () => {
339 console.log(`[api] listening on http://127.0.0.1:${API_PORT}`)
340})