-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathserver.js
76 lines (68 loc) · 1.61 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
72
73
74
75
76
const { faker } = require("@faker-js/faker");
const http = require("node:http");
const server = http.createServer({}, (req, res) => {
const url = new URL(
req.url || "/",
"http://localhost:8080"
);
const id = url.searchParams.get("id");
if (url.pathname === "/complex") {
res.writeHead(200, {
"Content-Type": "application/json",
});
return res.end(
JSON.stringify({
id: faker.string.uuid(),
name: faker.person.fullName(),
relatedPeople:
Math.random() > 0.5
? Array.from({ length: 5 }, () => ({
id: faker.string.uuid(),
name: faker.person.fullName(),
}))
: null,
})
);
}
if (req.method === "GET") {
res.writeHead(200, {
"Content-Type": "application/json",
});
return res.end(
JSON.stringify({
id,
name: "Check Lee",
})
);
}
if (req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
let parsedBody;
try {
parsedBody = JSON.parse(body);
console.log(parsedBody);
} catch (e) {
res.writeHead(400, {
"Content-Type": "application/json",
});
return res.end(
JSON.stringify({ error: "Invalid JSON" })
);
}
res.writeHead(201, {
"Content-Type": "application/json",
});
return res.end(
JSON.stringify({
id: faker.string.uuid(),
name: parsedBody.name,
})
);
});
}
});
server.listen(8000);