-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathcontrollers.js
More file actions
53 lines (47 loc) · 1.23 KB
/
controllers.js
File metadata and controls
53 lines (47 loc) · 1.23 KB
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
'use strict';
const { setCache } = require('./cache');
const { parseCookies } = require('./cookies');
const { personGetService, personPostService } = require('./services');
const defaultController = (req, res) => {
const cookies = parseCookies(req);
res.writeHead(200, {
'Set-Cookie': 'mycookie=test',
'Content-Type': 'text/html'
});
const ip = req.connection.remoteAddress;
res.write(`<h1>Welcome</h1>Your IP: ${ip}`);
res.end(`<pre>${JSON.stringify(cookies)}</pre>`);
}
const personGetController = async (req, res) => {
const result = await personGetService();
setCache(req.url, result);
if (result) {
res.writeHead(200);
res.end(result);
} else {
res.writeHead(500);
res.end('Read error');
}
}
const personPostController = (req, res) => {
const body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', async () => {
let data = Buffer.concat(body).toString();
const obj = JSON.parse(data);
data = await personPostService(obj);
if (data) {
res.writeHead(200);
res.end('File saved');
} else {
res.writeHead(500);
res.end('Write error');
}
});
}
module.exports = {
defaultController,
personGetController,
personPostController
}