-
Notifications
You must be signed in to change notification settings - Fork 1
/
athena.js
75 lines (62 loc) · 1.88 KB
/
athena.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
73
74
75
const { WebSocketServer } = require('ws');
const { JSONRPCServer, createJSONRPCErrorResponse } = require('json-rpc-2.0');
function heartbeat() {
this.isAlive = true;
}
const wss = new WebSocketServer({ port: 8080 });
const server = new JSONRPCServer();
wss.on('connection', function connection(ws) {
ws.isAlive = true;
ws.on('error', console.error);
ws.on('pong', heartbeat);
ws.on('message', function message(data) {
const jsonRPCRequest = JSON.parse(data);
if (!server.hasMethod(jsonRPCRequest.method)) {
console.log('received: %s', data);
}
server.receive(jsonRPCRequest).then((jsonRPCResponse) => {
if (jsonRPCResponse) {
ws.send(JSON.stringify(jsonRPCResponse));
}
});
});
// ws.send('something');
});
const interval = setInterval(function ping() {
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
wss.on('close', function close() {
clearInterval(interval);
});
// next will call the next middleware
const logMiddleware = (next, request, serverParams) => {
console.log(`Received ${JSON.stringify(request)}`);
return next(request, serverParams).then((response) => {
console.log(`Responding ${JSON.stringify(response)}`);
return response;
});
};
const exceptionMiddleware = async (next, request, serverParams) => {
try {
return await next(request, serverParams);
} catch (error) {
if (error.code) {
return createJSONRPCErrorResponse(request.id, error.code, error.message);
} else {
throw error;
}
}
};
// Middleware will be called in the same order they are applied
server.applyMiddleware(logMiddleware, exceptionMiddleware);
server.addMethod('forwardLogs', (params) => {
console.log(params);
return {"success": 1};
});
server.addMethod('storeStats', (params) => {
console.log(params);
});