52 lines
1.2 KiB
JavaScript
52 lines
1.2 KiB
JavaScript
import { WebSocketServer } from 'ws';
|
|
|
|
let wss;
|
|
let connections = [];
|
|
|
|
export function init(cfg, db) {
|
|
wss = new WebSocketServer(cfg);
|
|
|
|
wss.on('connection', ws => {
|
|
connections.push(ws);
|
|
|
|
ws.on('error', console.error);
|
|
ws.on('close', (e) => {
|
|
connections.splice(connections.indexOf(ws), 1);
|
|
});
|
|
ws.on('message', (data, isBinary) => {
|
|
try {
|
|
let message = JSON.parse(data);
|
|
|
|
switch (message.action) {
|
|
case "set":
|
|
db.persist(
|
|
message.subject,
|
|
message.filter,
|
|
message.field,
|
|
message.value
|
|
);
|
|
break;
|
|
case "subscribe":
|
|
db.subscribe(
|
|
message.subject,
|
|
message.filter
|
|
).then(r => ws.send(
|
|
JSON.stringify({
|
|
subject: message.subject,
|
|
field: message.field,
|
|
filter: message.filter,
|
|
value: r.map(v => v[message.field]),
|
|
})
|
|
));
|
|
break;
|
|
default:
|
|
throw 'invalid action "' + message.action + '"';
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
});
|
|
});
|
|
return wss;
|
|
}
|