-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-service.js
More file actions
33 lines (26 loc) · 795 Bytes
/
user-service.js
File metadata and controls
33 lines (26 loc) · 795 Bytes
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
const http = require('http');
const url = require('url');
const users = ['Aras', 'Arsy', 'Dimas', 'Ivan', 'Rafy', 'Gilang'];
const MISSING = 4;
const server = http.createServer((req, res) => {
const { pathname } = url.parse(req.url);
let id = pathname.match(/^\/(\d+)$/);
if (!id) {
res.statusCode = 400;
return void res.end();
}
id = Number(id[1]);
if (id === MISSING) {
res.statusCode = 404;
return void res.end();
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
id,
name: users[id % users.length],
}));
});
server.listen(process.env.PORT || 0, () => {
const { port } = server.address();
console.log(`User service listening on localhost on port: ${port}`);
});