-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.ts
76 lines (60 loc) · 2.33 KB
/
rest.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
66
67
68
69
70
71
72
73
74
75
76
import { Server } from "http";
import { Data } from '@async-reactivity-sample/business-logic';
import { getBody } from "./utils.js";
export default (server: Server) => {
server.on('request', async (req, res) => {
const url = new URL(req.url ?? '', 'http://localhost:8080');
if (req.method === 'GET' && url.pathname === '/items') {
if (!url.searchParams.get('token')) {
res.writeHead(401);
res.end();
return;
}
const filters = {
done: url.searchParams.get('done') !== null ? url.searchParams.get('done') === 'true' : null,
text: url.searchParams.get('text')
};
const items = await Data.list();
const result = items.filter(i =>
(filters.done === null || i.done === filters.done)
&& (!filters.text || i.text.includes(filters.text))
);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
}
if (req.method === 'PATCH' && url.pathname.startsWith('/items/')) {
if (!url.searchParams.get('token')) {
res.writeHead(401);
res.end();
return;
}
const id = url.pathname.replace('/items/', '');
const body = await getBody(req);
const item = await Data.get(id);
if (!item) {
res.writeHead(404);
res.end();
return;
}
for (const [prop, value] of Object.entries(body)) {
// @ts-expect-error
item[prop] = value;
}
Data.write();
res.writeHead(204);
res.end();
}
if (req.method === 'DELETE' && url.pathname.startsWith('/items')) {
if (!url.searchParams.get('token')) {
res.writeHead(401);
res.end();
return;
}
const id = url.pathname.replace('/items/', '');
await Data.remove(id);
Data.write();
res.writeHead(204);
res.end();
}
});
};