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

api-handlers.ts

32 lines992 Bytes

1import { HttpResponse, http } from 'msw'
2import { posts } from './posts.ts'
3import { users } from './users.ts'
4​
5export const apiHandlers = [
6 ...Object.entries({ posts, users }).flatMap(([resource, data]) => [
7 http.get(`https://jsonplaceholder.typicode.com/${resource}`, () =>
8 HttpResponse.json(data),
9 ),
10 http.get(
11 `https://jsonplaceholder.typicode.com/${resource}/:id`,
12 ({ params }) => {
13 const id = parseInt(String(params.id))
14 if (Number.isNaN(id)) {
15 return HttpResponse.json(
16 { error: `invalid ${resource.slice(0, -1)} id` },
17 { status: 404 },
18 )
19 }
20 const item = data.find((entry) => entry.id === id)
21 return item
22 ? HttpResponse.json(item)
23 : new HttpResponse(null, {
24 headers: { 'content-type': 'application/json' },
25 })
26 },
27 ),
28 ]),
29 http.all('https://jsonplaceholder.typicode.com/*', () =>
30 HttpResponse.error(),
31 ),