-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathws.js
39 lines (35 loc) · 1.1 KB
/
ws.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
'use strict';
const { Server } = require('ws');
module.exports = (routing, port, console) => {
const ws = new Server({ port });
ws.on('connection', (connection, req) => {
const ip = req.socket.remoteAddress;
connection.on('message', async (message) => {
const obj = JSON.parse(message);
const { name, method, args = [] } = obj;
const entity = routing[name];
if (!entity) {
connection.send('"Not found"', { binary: false });
return;
}
const handler = entity[method];
if (!handler) {
connection.send('"Not found"', { binary: false });
return;
}
const json = JSON.stringify(args);
const parameters = json.substring(1, json.length - 1);
console.log(`${ip} ${name}.${method}(${parameters})`);
try {
const result = await handler(...args);
connection.send(
JSON.stringify(result), { binary: false }
);
} catch (err) {
console.error(err);
connection.send('"Server error"', { binary: false });
}
});
});
console.log(`API on port ${port}`);
};