Open History to see the last commit
1import { HttpResponse, delay, http, passthrough } from 'msw'
2import { setupWorker } from 'msw/browser'
3β
4const movies = [
5 {
6 id: '1',
7 title: 'Guardians of the Galaxy',
8 comment: '',
9 },
10 {
11 id: '2',
12 title: 'Wall-E',
13 comment: '',
14 },
15]
16β
17export const fetchMovie = async (
18 id: string,
19): Promise<{
20 ts: number
21 movie: { comment: string; id: string; title: string }
22}> => {
23 const response = await fetch(`/movies/${id}`)
24 if (!response.ok) {
25 throw new Error(await response.text())
26 }
27 return await response.json()
28}
29β
30export const fetchMovies = async (): Promise<{
31 ts: number
32 movies: Array<{ id: string; title: string }>
33}> => {
34 const response = await fetch('/movies')
35 if (!response.ok) {
36 throw new Error(await response.text())
37 }
38 return await response.json()
39}
40β
41export const updateMovie = async (
42 id: string,
43 comment: string,
44): Promise<{ message: string }> => {
45 const response = await fetch(`/movies/${id}`, {
46 method: 'POST',
47 body: JSON.stringify({ comment }),
48 headers: { 'Content-Type': 'application/json' },
49 })
50 if (!response.ok) {
51 throw new Error(await response.text())
52 }
53 return await response.json()
54}
55β
56export const worker = setupWorker(
57 http.get('/movies', async () => {
58 await delay(500)
59 return HttpResponse.json({
60 ts: Date.now(),
61 movies: movies.map(({ id, title }) => ({ id, title })),
62 })
63 }),
64β
65 http.get('/movies/:id', async ({ params }) => {
66 const { id } = params
67β
68 const movie = movies.find((item) => item.id === id)
69β
70 if (!movie) {
71 return new HttpResponse(`Movie with id ${id} not found`, {
72 status: 404,
73 })
74 }
75β
76 await delay(500)
77 return HttpResponse.json({ ts: Date.now(), movie })
78 }),
79β
80 http.post<{ id: string }, { comment: string }>(
81 '/movies/:id',
82 async ({ request, params }) => {
83 const { id } = params
84 const body = await request.json()
85 const { comment } = body
86β
87 movies.forEach((movie) => {
88 if (movie.id === id) {
89 movie.comment = comment.toUpperCase()
90 }
91 })
92β
93 await delay(500)
94 return HttpResponse.json({ message: `Successfully updated movie ${id}` })
95 },
96 ),
97 http.get('*.js', () => passthrough()),
98 http.get('*.svg', () => passthrough()),
99)