UNPKG

@jsonjoy.com/reactive-rpc

Version:

Reactive-RPC is a library for building reactive APIs over WebSocket, HTTP, and other RPCs.

77 lines 3.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StaticRpcClient = void 0; const tslib_1 = require("tslib"); const msg = tslib_1.__importStar(require("../../messages")); const TimedQueue_1 = require("../../util/TimedQueue"); const Value_1 = require("../../messages/Value"); const Defer_1 = require("../../../util/Defer"); const rxjs_1 = require("rxjs"); class StaticRpcClient { constructor({ send, bufferSize = 100, bufferTime = 10 }) { this.id = 1; this.onsend = async () => { throw new Error('onsend not implemented'); }; this.calls = new Map(); if (send) this.onsend = send; this.buffer = new TimedQueue_1.TimedQueue(); this.buffer.itemLimit = bufferSize; this.buffer.timeLimit = bufferTime; this.buffer.onFlush = (messages) => { this.onsend(messages) .then((responses) => { for (const response of responses) { const id = response.id; const calls = this.calls; const future = calls.get(id); calls.delete(id); if (!future) continue; if (response instanceof msg.ResponseCompleteMessage) future.resolve(response.value?.data); else if (response instanceof msg.ResponseErrorMessage) future.reject(response.value?.data); } }) .catch((error) => { for (const message of messages) if (message instanceof msg.RequestCompleteMessage) { const id = message.id; const calls = this.calls; const future = calls.get(id); calls.delete(id); if (!future) continue; future.reject(error); } }) .finally(() => { for (const message of messages) if (message instanceof msg.RequestCompleteMessage) this.calls.delete(message.id); }); }; } call$(method, data) { return (data instanceof rxjs_1.Observable ? data : (0, rxjs_1.of)(data)).pipe((0, rxjs_1.switchMap)((data) => this.call(method, data))); } async call(method, request) { const id = this.id; this.id = (id + 1) % 0xffff; const value = new Value_1.RpcValue(request, undefined); const message = new msg.RequestCompleteMessage(id, method, value); const future = new Defer_1.Defer(); this.calls.set(id, future); this.buffer.push(message); return await future.promise; } notify(method, data) { const value = new Value_1.RpcValue(data, undefined); this.buffer.push(new msg.NotificationMessage(method, value)); } stop() { } } exports.StaticRpcClient = StaticRpcClient; //# sourceMappingURL=StaticRpcClient.js.map