UNPKG

@quo0/stiletto

Version:

With stiletto library you will be able to mock requests and choose between preconfigured responses right on the fly via UI

57 lines 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebsocketServerService = void 0; const tslib_1 = require("tslib"); const constants_1 = require("../../constants"); const inversify_1 = require("inversify"); const ws_1 = require("ws"); const rxjs_1 = require("rxjs"); let WebsocketServerService = class WebsocketServerService { constructor() { this.isReadySubject$ = new rxjs_1.BehaviorSubject(false); this.messagesSubject$ = new rxjs_1.Subject(); this.errorSubject$ = new rxjs_1.Subject(); this.closeSubject$ = new rxjs_1.Subject(); this.isReady$ = this.isReadySubject$.asObservable(); this.messages$ = this.messagesSubject$.asObservable(); this.error$ = this.errorSubject$.asObservable(); this.close$ = this.closeSubject$.asObservable(); } get port() { return constants_1.STILETTO_WS_PORT; // TODO: should we provide ability to set custom port? } launch() { const wss = new ws_1.WebSocketServer({ port: this.port }); console.log('WS server is launched'); wss.on('connection', (ws) => { this.ws = ws; this.isReadySubject$.next(true); ws.on('message', (rawData) => { const message = JSON.parse(rawData.toString()); this.messagesSubject$.next(message); }); ws.on('error', (error) => { this.errorSubject$.next(error); this.isReadySubject$.next(false); }); ws.on('close', (exitStatus) => { this.closeSubject$.next(exitStatus); this.isReadySubject$.next(false); }); }); } ; sendMessage(message) { if (this.ws) { this.ws.send(JSON.stringify(message)); } else { console.error('trying to send ws message, but no connection has been established!'); } } }; WebsocketServerService = (0, tslib_1.__decorate)([ (0, inversify_1.injectable)() ], WebsocketServerService); exports.WebsocketServerService = WebsocketServerService; //# sourceMappingURL=websocket-server.service.js.map