-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
db.ts
65 lines (55 loc) · 1.4 KB
/
db.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { factory, primaryKey } from '@mswjs/data'
import { nanoid } from '@reduxjs/toolkit'
import { rest } from 'msw'
import { Post } from '../app/services/posts'
const db = factory({
post: {
id: primaryKey(String),
name: String,
},
})
;[
'A sample post',
'A post about RTK Query',
'How to randomly throw errors, a novella',
].forEach((name) => {
db.post.create({ id: nanoid(), name })
})
export const handlers = [
rest.post('/posts', async (req, res, ctx) => {
const { name } = req.body as Partial<Post>
if (Math.random() < 0.3) {
return res(
ctx.json({ error: 'Oh no, there was an error, try again.' }),
ctx.status(500),
ctx.delay(300),
)
}
const post = db.post.create({
id: nanoid(),
name,
})
return res(ctx.json(post), ctx.delay(300))
}),
rest.put('/posts/:id', (req, res, ctx) => {
const { name } = req.body as Partial<Post>
if (Math.random() < 0.3) {
return res(
ctx.json({ error: 'Oh no, there was an error, try again.' }),
ctx.status(500),
ctx.delay(300),
)
}
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id
const post = db.post.update({
where: {
id: {
equals: id,
},
},
data: { name },
})
return res(ctx.json(post), ctx.delay(300))
}),
...db.post.toHandlers('rest'),
] as const