-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
96 lines (80 loc) · 2.25 KB
/
main.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const http = require('http');
const path = require('path');
const fs = require('fs');
const Mustache = require('mustache');
const { isEmpty } = require('lodash');
const { dbClient } = require('./yourNoSql');
const { serveStatic } = require('./serveStatic');
const PORT = process.env.PORT || 9090;
const templateList = {
userList: {
content: null,
fileName: path.join(__dirname, 'templates/userList.html'),
},
user: {
content: null,
fileName: path.join(__dirname, 'templates/user.html'),
},
};
/**
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
async function listener(req, res) {
if (req.method !== 'GET') {
res.statusCode = 405;
res.end();
return;
}
if (req.url === '/' || req.url === '/users' || req.url === '/users/') {
res.writeHead(302, {
Location: '/users.html',
});
res.end();
return;
}
if (req.url === '/users.html') {
const users = await dbClient.getList();
// pending
// resolved
// rejected
res.statusCode = 200;
const content = Mustache.render(templateList.userList.content, { title: 'User List from data', users });
res.write(content);
res.end();
return;
}
if (req.url.startsWith('/users/')) {
const baseURL = `http://${req.headers.host}/`;
const myURL = new URL(req.url, baseURL);
const [,, id] = myURL.pathname.split('/');
const userUpdateData = Object.fromEntries(myURL.searchParams.entries());
if (isEmpty(myURL.search)) {
const user = await dbClient.findUser(id);
const content = Mustache.render(templateList.user.content, user);
res.write(content);
res.end();
return;
}
await dbClient.update(id, userUpdateData);
res.writeHead(302, {
Location: '/users.html',
});
res.end();
return;
}
serveStatic(req, res);
}
const server = http.createServer(listener);
function listenIfReady() {
const allLoaded = Object.values(templateList).every((template) => template.content);
if (allLoaded) {
server.listen(PORT);
}
}
Object.entries(templateList).forEach(([templateName, template]) => {
fs.readFile(template.fileName, 'utf-8', (err, userListContent) => {
templateList[templateName].content = userListContent;
listenIfReady();
});
});