UNPKG

ps2census

Version:

Client to connect to the PS2 Event Stream websocket.

84 lines 3.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CommandHandler = void 0; const queue_1 = require("./utils/queue"); const stream_response_exception_1 = require("./exceptions/stream-response.exception"); class CommandHandler { constructor(stream) { this.stream = stream; this.subscriptionQueue = new queue_1.Queue(); this.recentCharacterQueue = new queue_1.Queue(); this.prepareListeners(); } prepareListeners() { this.stream.on('message', msg => { if ('service' in msg && msg.service === 'event' && msg.type == 'serviceMessage' && 'recent_character_id_count' in msg.payload) { this.recentCharacterQueue.dequeue().resolve(msg.payload); } else if ('subscription' in msg) { this.subscriptionQueue.dequeue().resolve(msg.subscription); } }); this.stream.on('close', () => { while (this.subscriptionQueue.size) this.subscriptionQueue .dequeue() .reject(new stream_response_exception_1.StreamResponseException('Stream closed before receiving response')); while (this.recentCharacterQueue.size) this.recentCharacterQueue .dequeue() .reject(new stream_response_exception_1.StreamResponseException('Stream closed before receiving response')); }); } subscribe(subscription) { return this.sendCommand(this.subscriptionQueue, { service: 'event', action: 'subscribe', ...subscription, }); } clearSubscribe(subscription) { return this.sendCommand(this.subscriptionQueue, { service: 'event', action: 'clearSubscribe', ...subscription, }); } async clearSubscribeAll() { await this.sendCommand(this.subscriptionQueue, { service: 'event', action: 'clearSubscribe', all: 'true', }); } async recentCharacters() { const { recent_character_id_list } = await this.sendCommand(this.recentCharacterQueue, { service: 'event', action: 'recentCharacterIds', }); return recent_character_id_list; } async recentCharacterCount() { const { recent_character_id_count } = await this.sendCommand(this.recentCharacterQueue, { service: 'event', action: 'recentCharacterIds', }); return recent_character_id_count; } sendCommand(queue, command) { if (!this.stream.isReady) return Promise.reject(new stream_response_exception_1.StreamResponseException('Stream is closed')); return new Promise((resolve, reject) => { this.stream.send(command); queue.enqueue({ resolve, reject, }); }); } } exports.CommandHandler = CommandHandler; //# sourceMappingURL=command.handler.js.map