-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (67 loc) · 1.81 KB
/
server.js
File metadata and controls
72 lines (67 loc) · 1.81 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
const http = require('http');
const Client = require('./client.js');
const Session = require('./session.js');
const routing = {
'/': async client => '<h1>welcome to homepage</h1><hr>',
'/start': async client => {
Session.start(client);
return `Session token is: ${client.token}`;
},
'/destroy': async client => {
const result = `Session destroyed: ${client.token}`;
Session.delete(client);
return result;
},
'/api/method1': async client => {
if (client.session) {
client.session.set('method1', 'called');
return { data: 'example result' };
} else {
return { data: 'access is denied' };
}
},
'/api/method2': async client => ({
url: client.req.url,
headers: client.req.headers,
}),
'/api/method3': async client => {
if (client.session) {
return [...client.session.entries()].map(([key, value]) => {
return `<b>${key}</b>: ${value}<br>`;
}).join();
}
return 'No session found';
},
};
const types = {
object: JSON.stringify,
string: s => s,
number: n => n.toString(),
undefined: () => 'not found',
};
http.createServer(async (req, res) => {
const client = await Client.getInstance(req, res);
const { method, url, headers } = req;
console.log(`${method} ${url} ${headers.cookie}`);
const handler = routing[url];
res.on('finish', () => {
if (client.session) client.session.save();
});
if (handler) {
handler(client)
.then(data => {
const type = typeof data;
const serializer = types[type];
const result = serializer(data);
client.sendCookie();
res.end(result);
}, err => {
res.statusCode = 500;
res.end('Internal Server Error 500');
});
return;
}
res.statusCode = 404;
res.end('Not found 404');
}).listen(8000);