-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathserver.js
More file actions
50 lines (42 loc) · 1.25 KB
/
server.js
File metadata and controls
50 lines (42 loc) · 1.25 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
'use strict';
const http = require('node:http');
const PORT = 8000;
const HANDLER_LENGTH = 3;
const user = { name: 'jura', age: 22 };
const routing = {
'/': '<h1>welcome to homepage</h1><hr>',
'/user': user,
'/user/name': () => user.name.toUpperCase(),
'/user/age': () => user.age,
'/hello': { hello: 'world', andArray: [1, 2, 3, 4, 5, 6, 7] },
'/api/method1': (req, res, callback) => {
console.log(req.url + ' ' + res.statusCode);
callback({ status: res.statusCode });
},
'/api/method2': (req) => ({
user,
url: req.url,
cookie: req.headers.cookie,
}),
};
const types = {
object: ([data], callback) => callback(JSON.stringify(data)),
undefined: (args, callback) => callback('not found'),
function: ([fn, req, res], callback) => {
if (fn.length === HANDLER_LENGTH) fn(req, res, callback);
else callback(JSON.stringify(fn(req, res)));
},
};
const serve = (data, req, res) => {
const type = typeof data;
if (type === 'string') return void res.end(data);
const serializer = types[type];
serializer([data, req, res], (ser) => serve(ser, req, res));
};
http
.createServer((req, res) => {
const data = routing[req.url];
serve(data, req, res);
})
.listen(PORT);
setInterval(() => user.age++, 2000);