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 return await response.json()
25}
26β
27export const fetchMovies = async (): Promise<{
28 ts: number
29 movies: typeof movies
30}> => {
31 const response = await fetch('/movies')
32 return await response.json()
33}
34β
35export const updateMovie = async (id: string, comment: string) => {
36 const response = await fetch(`/movies/${id}`, {
37 method: 'POST',
38 body: JSON.stringify({ comment }),
39 headers: { 'Content-Type': 'application/json' },
40 })
41 return await response.json()
42}
43β
44export const worker = setupWorker(
45 http.get('/movies', async () => {
46 await delay(500)
47 return HttpResponse.json({
48 ts: Date.now(),
49 movies: movies.map(({ id, title }) => ({ id, title })),
50 })
51 }),
52β
53 http.get('/movies/:id', async ({ params }) => {
54 const { id } = params
55β
56 const movie = movies.find((movie) => movie.id === id)
57β
58 if (!movie) {
59 return new HttpResponse(`Movie with id ${id} not found`, {
60 status: 404,
61 })
62 }
63β
64 await delay(500)
65 return HttpResponse.json({ ts: Date.now(), movie })
66 }),
67β
68 http.post('/movies/:id', async ({ request, params }) => {
69 const { id } = params
70 const body = (await request.json()) as { comment: string }
71 const { comment } = body
72β
73 movies.forEach((movie) => {
74 if (movie.id === id) {
75 movie.comment = comment.toUpperCase()
76 }
77 })
78β
79 await delay(500)
80 return HttpResponse.json({ message: `Successfully updated movie ${id}` })
81 }),
82 http.get('*.js', () => passthrough()),
83 http.get('*.svg', () => passthrough()),
84)