-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4-server.js
More file actions
74 lines (62 loc) · 1.62 KB
/
4-server.js
File metadata and controls
74 lines (62 loc) · 1.62 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
'use strict';
const http = require('node:http');
const handlers = Symbol('handlers');
class Server {
constructor(port) {
this.port = port;
this.http = http.createServer((req, res) => {
this.request(req, res);
});
this.routing = { [handlers]: [] };
this.http.listen(port);
}
async handler(path, handler) {
const dirs = path.split('/');
const current = this.routing;
let next;
for (const dir of dirs) {
next = current[dir];
if (!next) {
current[dir] = { [handlers]: [handler] };
}
}
}
async request(req, res) {
const dirs = req.url.substring[1].split('/');
console.dir({ dirs });
const current = this.routing;
for (const dir of dirs) {
const next = current[dir];
if (!next) return;
const listeners = next[handlers];
await this.chain(req, res, listeners);
}
}
async chain(req, res, listeners) {
for (const listener of listeners) {
await listener(req, res);
}
}
}
// Usage
const server = new Server(8000);
server.handler('/api', async (req, res) => {
console.log('Request to /api');
res.end('It works!');
});
server.handler('/api', async (req, res) => {
console.log('Remote address: ' + res.socket.remoteAddress);
res.end('It works!');
});
server.handler('/api/v1', async (req, res) => {
console.log('Request to /api/v1');
res.end('It works!');
});
server.handler('/api/v1/method', async (req, res) => {
console.log('Call: /api/v1/method');
res.end('It works!');
});
server.handler('/api/v1/method', async (req, res) => {
console.log('Should not be executed');
res.end('It works!');
});