-
Notifications
You must be signed in to change notification settings - Fork 0
/
generateApi.ts
55 lines (51 loc) · 1.45 KB
/
generateApi.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
import { IncomingMessage, ServerResponse } from "http";
import { Repository } from "../types/dbAdapter";
export const apiHandler =
<T>(repo: Repository<T>) =>
async (req: IncomingMessage, res: ServerResponse) => {
const url = new URL(req.url, "http://localhost");
const [,subject, id] = url.pathname.split("/");
if (subject !== repo.name()) {
return false;
}
const body = await new Promise((resolve) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
try {
resolve(JSON.parse(body));
} catch {
resolve(null);
}
});
});
const data = await (async () => {
if (!id && req.method === "GET") {
const filters = (() => {
try {
return JSON.parse(url.searchParams.get('filters'));
} catch {
return [];
}
})();
return repo.readMany(filters ?? []);
}
if (id && req.method === "GET") {
return repo.read(id);
}
if (!id && req.method === "POST") {
return repo.create(body as any);
}
if (id && req.method === "PUT") {
return repo.update(id as any, body as any);
}
if (id && req.method === "DELETE") {
return repo.delete(id as any);
}
})();
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(data));
return true;
};