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

api.ts

90 lines2.0 KB

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