Open History to see the last commit
1import { setupWorker, rest } from 'msw'
2import ky from 'ky'
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 = (id) => ky.get(`/movies/${id}`).json()
18export const fetchMovies = () => ky.get('/movies').json()
19export const updateMovie = (id, comment) =>
20 ky.post(`/movies/${id}`, { json: { comment } }).json()
21β
22export const worker = setupWorker(
23 ...[
24 rest.get('/movies', (req, res, ctx) => {
25 return res(
26 ctx.delay(1000),
27 ctx.json({
28 ts: Date.now(),
29 movies: movies.map(({ id, title }) => ({ id, title })),
30 }),
31 )
32 }),
33 rest.get('/movies/:id', (req, res, ctx) => {
34 const { id } = req.params
35β
36 const movie = movies.find((movie) => movie.id === id)
37 if (!movie) {
38 return res(ctx.status(404, `Movie with id ${id} not found`))
39 }
40β
41 return res(
42 ctx.delay(1000),
43 ctx.json({
44 ts: Date.now(),
45 movie,
46 }),
47 )
48 }),
49 rest.post('/movies/:id', (req, res, ctx) => {
50 const { id } = req.params
51 const { comment } = req.body
52β
53 movies.forEach((movie) => {
54 if (movie.id === id) {
55 movie.comment = comment.toUpperCase()
56 }
57 })
58β
59 return res(
60 ctx.delay(1000),
61 ctx.json({
62 message: `Successfully updated movie ${id}`,
63 }),
64 )
65 }),
66 ],
67)