-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.ts
More file actions
66 lines (51 loc) · 1.84 KB
/
handlers.ts
File metadata and controls
66 lines (51 loc) · 1.84 KB
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
66
import { seed } from "@ngneat/falso";
import { http, HttpResponse } from "msw";
import { api } from "../api";
import { createNoteMock } from "../api/note/mocks";
import { CreateNoteSchema } from "../api/note/schema";
seed("42");
const defaults = [createNoteMock({}), createNoteMock({}), createNoteMock({}), createNoteMock({})];
let mockNotes = structuredClone(defaults);
export const resetMockNotes = () => {
mockNotes = structuredClone(defaults);
};
export const getMockNotes = () => {
return mockNotes;
};
export const handlers = [
http.get(api.notes.get.url, ({ params }) => {
const { noteId } = params;
return HttpResponse.json(mockNotes.find((n) => n.id === noteId));
}),
http.get(api.notes.getAll.url, ({ request }) => {
const url = new URL(request.url);
const search = url.searchParams.get("search");
if (search) {
return HttpResponse.json(
mockNotes.filter((n) => n.title.toLowerCase().includes(search.toLowerCase())),
);
}
return HttpResponse.json(mockNotes);
}),
http.post(api.notes.create.url, async ({ request }) => {
const newNote = CreateNoteSchema.safeParse(await request.json());
if (!newNote.success) {
return HttpResponse.json(newNote.error.flatten(), { status: 400 });
}
mockNotes.push({ ...newNote.data, id: crypto.randomUUID() });
return HttpResponse.json(newNote, { status: 201 });
}),
http.put(api.notes.edit.url, async ({ request, params }) => {
const { noteId } = params;
const newNote = CreateNoteSchema.safeParse(await request.json());
const existingNote = mockNotes.find((n) => n.id === noteId);
if (!existingNote) {
return HttpResponse.json({}, { status: 404 });
}
if (!newNote.success) {
return HttpResponse.json(newNote.error.flatten(), { status: 400 });
}
Object.assign(existingNote, newNote.data);
return HttpResponse.json(existingNote, { status: 200 });
}),
];