-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (74 loc) · 1.92 KB
/
server.js
File metadata and controls
80 lines (74 loc) · 1.92 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
73
74
75
76
77
78
79
80
'use strict';
const http = require('node:http');
const Client = require('./client.js');
const Session = require('./session.js');
const INVALID_TOKEN_CODE = 498;
const routing = {
'/': async () => '<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]) => `<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) => {
try {
const client = await Client.getInstance(req, res);
} catch {
res.statusCode = INVALID_TOKEN_CODE;
res.end();
return;
}
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) {
res.statusCode = 404;
res.end('Not found 404');
return;
}
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');
console.log(err);
});
}).listen(8000);