@lesy/lesy-plugin-pilot
Version:
59 lines (58 loc) • 1.84 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketBus = void 0;
const ws_1 = require("ws");
const rxjs_1 = require("rxjs");
const json_stringify_safe_1 = __importDefault(require("json-stringify-safe"));
class WebSocketBus {
constructor() {
this.receiver = new rxjs_1.Subject();
this.sender = new rxjs_1.Subject();
}
startServer(host, port) {
this.ws = new ws_1.Server({ host, port });
this.ws.on("open", this.onConnectionOpen);
this.ws.on("close", this.onConnectionClosed);
return this;
}
init(requests) {
this.requests = requests;
this.ws.on("connection", (ws) => {
this.sender.subscribe((a) => {
ws.send(JSON.stringify(a));
});
ws.on("message", (message) => this.onMessageReceived.call(this, message, ws));
});
return this;
}
sendMessage(message) {
this.sender.next(message);
}
listen() {
return this.receiver.asObservable();
}
close(cb) {
this.sender.unsubscribe();
this.receiver.unsubscribe();
this.ws.close(cb);
}
onConnectionOpen() {
console.log("conneted");
}
onConnectionClosed() {
console.log("disconneted");
}
async onMessageReceived(message, ws) {
const data = JSON.parse(message);
this.receiver.next(data);
if (!this.requests[data.REQUEST])
return;
const response = await this.requests[data.REQUEST](data.PAYLOAD);
if (response)
ws.send(json_stringify_safe_1.default(response));
}
}
exports.WebSocketBus = WebSocketBus;