-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
72 lines (63 loc) · 1.67 KB
/
server.js
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('node:http');
const path = require('node:path');
const fs = require('node:fs').promises;
const { Scheduler } = require('./scheduler.js');
global.scheduler = new Scheduler();
const api = new Map();
const apiPath = './api/';
const cacheFile = (name) => {
const filePath = apiPath + name;
const key = path.basename(filePath, '.js');
try {
const libPath = require.resolve(filePath);
delete require.cache[libPath];
} catch (e) {
return;
}
try {
const method = require(filePath);
api.set(key, method);
} catch (e) {
api.delete(name);
}
};
const cacheFolder = async (path) => {
const files = await fs.readdir(path);
for (const file of files) {
await cacheFile(file);
}
};
const receiveArgs = async (req) => {
const buffers = [];
for await (const chunk of req) buffers.push(chunk);
return Buffer.concat(buffers).toString();
};
const httpError = (res, status, message) => {
res.statusCode = status;
res.end(`"${message}"`);
};
const start = async () => {
http.createServer(async (req, res) => {
const [first, second] = req.url.substring(1).split('/');
if (first === 'api') {
const method = api.get(second);
const args = await receiveArgs(req);
try {
const result = await method(...args);
if (!result) {
httpError(res, 500, 'Server error');
return;
}
res.end(JSON.stringify(result));
} catch (err) {
console.dir({ err });
httpError(res, 500, 'Server error');
}
}
}).listen(8000);
await cacheFolder(apiPath);
console.dir({ api });
console.log('Server started');
};
module.exports = { start };