Open History to see the last commit
1import { HttpResponse, delay, http } from 'msw'
2import { setupWorker } from 'msw/browser'
3import type { Todo } from './services/todos/types'
4β
5const todos: Array<Todo> = [
6 {
7 id: crypto.randomUUID(),
8 text: 'Buy groceries',
9 createdAt: Date.now() - 3000,
10 },
11 {
12 id: crypto.randomUUID(),
13 text: 'Walk the dog',
14 createdAt: Date.now() - 2000,
15 },
16 {
17 id: crypto.randomUUID(),
18 text: 'Read a book',
19 createdAt: Date.now() - 1000,
20 },
21]
22β
23export const worker = setupWorker(
24 http.get('/api/todos', async () => {
25 await delay(200)
26 return HttpResponse.json(todos)
27 }),
28β
29 http.post('/api/todos', async ({ request }) => {
30 let body: unknown
31 try {
32 body = await request.json()
33 } catch {
34 return HttpResponse.json({ error: 'text is required' }, { status: 400 })
35 }
36β
37 const text =
38 body !== null &&
39 typeof body === 'object' &&
40 'text' in body &&
41 typeof body.text === 'string'
42 ? body.text.trim()
43 : ''
44β
45 if (!text) {
46 return HttpResponse.json({ error: 'text is required' }, { status: 400 })
47 }
48β
49 await delay(500)
50β
51 if (Math.random() < 0.3) {
52 return HttpResponse.json(
53 { error: 'Server error β please try again' },
54 { status: 500 },
55 )
56 }
57β
58 const newTodo: Todo = {
59 id: crypto.randomUUID(),
60 text,
61 createdAt: Date.now(),
62 }
63β
64 todos.push(newTodo)
65β
66 return HttpResponse.json(newTodo, { status: 201 })
67 }),
68)