-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
71 lines (71 loc) · 2.11 KB
/
server.js
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
// Dependencies
import { serve, write } from "bun";
// Import users json file
import users from "./users.json";
// Create server
serve({
async fetch(request) {
// Get url and method
const { url, method } = request;
// Get pathname from url
const { pathname } = new URL(url);
// Get All Users
if (pathname === "/api/users" && method === "GET") {
return new Response(JSON.stringify(users), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-control-allow-origin": "*",
},
});
}
// Create User
if (pathname === "/api/users" && method === "POST") {
const body = await request.json();
const newJson = users.concat(body);
write("./users.json", JSON.stringify(newJson), null, 2);
return new Response(JSON.stringify(newJson), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-control-allow-origin": "*",
},
});
}
// Delete User
// method == 0 is a DELETE request
if (pathname === "/api/users" && method == 0) {
const body = await request.json();
const newJson = users.filter((user) => user.id !== body.id);
write("./users.json", JSON.stringify(newJson), null, 2);
return new Response(JSON.stringify(newJson), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-control-allow-origin": "*",
},
});
}
// Update User
if (pathname === "/api/users" && method === "PUT") {
const body = await request.json();
const newJson = users.map((user) => {
if (user.id === body.id) {
return body;
}
return user;
});
write("./users.json", JSON.stringify(newJson), null, 2);
return new Response(JSON.stringify(newJson), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-control-allow-origin": "*",
},
});
}
// Send 404
return new Response("", { status: 404 });
},
});
console.log("Server running on port 3000");