|
1 | 1 | import { http, HttpResponse } from "msw";
|
2 | 2 |
|
| 3 | +interface Todo { |
| 4 | + id: number; |
| 5 | + title: string; |
| 6 | + content: string; |
| 7 | + isDone: boolean; |
| 8 | +} |
| 9 | + |
| 10 | +const todos: Todo[] = []; |
| 11 | + |
3 | 12 | export const handlers = [
|
4 | 13 | http.get("/api", () => {
|
5 | 14 | return HttpResponse.json({ message: "hello" });
|
6 | 15 | }),
|
| 16 | + |
| 17 | + http.get("/api/todos", () => { |
| 18 | + return HttpResponse.json(todos); |
| 19 | + }), |
| 20 | + |
| 21 | + http.post("/api/todos", (req) => { |
| 22 | + const body = req.request.body as Partial<Todo>; |
| 23 | + |
| 24 | + if (!body) return HttpResponse.json({ message: "body is required" }, { status: 400 }); |
| 25 | + |
| 26 | + const { title, content } = body; |
| 27 | + |
| 28 | + if (title === undefined || content === undefined) { |
| 29 | + return HttpResponse.json({ message: "title, content are required" }, { status: 400 }); |
| 30 | + } |
| 31 | + |
| 32 | + const newTodo: Todo = { |
| 33 | + id: todos.length + 1, |
| 34 | + title, |
| 35 | + content, |
| 36 | + isDone: false, |
| 37 | + }; |
| 38 | + |
| 39 | + todos.push(newTodo); |
| 40 | + |
| 41 | + return HttpResponse.json({ message: "success", post: newTodo }); |
| 42 | + }), |
| 43 | + |
| 44 | + http.put("/api/todos/:id", (req) => { |
| 45 | + const { id } = req.params; |
| 46 | + const body = req.request.body as Partial<Todo>; |
| 47 | + |
| 48 | + if (!body) return HttpResponse.json({ message: "body is required" }, { status: 400 }); |
| 49 | + |
| 50 | + const todo = todos.find((todo) => todo.id === Number(id)); |
| 51 | + |
| 52 | + if (!todo) return HttpResponse.json({ message: "todo not found" }, { status: 404 }); |
| 53 | + |
| 54 | + Object.assign(todo, body); |
| 55 | + |
| 56 | + return HttpResponse.json({ message: "success", todo }); |
| 57 | + }), |
| 58 | + |
| 59 | + http.delete("/api/todos/:id", (req) => { |
| 60 | + const { id } = req.params; |
| 61 | + |
| 62 | + const index = todos.findIndex((todo) => todo.id === Number(id)); |
| 63 | + |
| 64 | + if (index === -1) return HttpResponse.json({ message: "todo not found" }, { status: 404 }); |
| 65 | + |
| 66 | + todos.splice(index, 1); |
| 67 | + |
| 68 | + return HttpResponse.json({ message: "success" }); |
| 69 | + }), |
7 | 70 | ];
|
0 commit comments