Skip to content

Commit 554c65a

Browse files
committed
feat: todo mock api
1 parent bf6418d commit 554c65a

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Diff for: src/mocks/postHandler.ts

+63
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,70 @@
11
import { http, HttpResponse } from "msw";
22

3+
interface Todo {
4+
id: number;
5+
title: string;
6+
content: string;
7+
isDone: boolean;
8+
}
9+
10+
const todos: Todo[] = [];
11+
312
export const handlers = [
413
http.get("/api", () => {
514
return HttpResponse.json({ message: "hello" });
615
}),
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+
}),
770
];

0 commit comments

Comments
 (0)