UNPKG

@jsonjoy.com/reactive-rpc

Version:

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

61 lines 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RpcPersistentClient = void 0; const rxjs_1 = require("rxjs"); const operators_1 = require("rxjs/operators"); const StreamingRpcClient_1 = require("./client/StreamingRpcClient"); const channel_1 = require("../channel"); class RpcPersistentClient { constructor(params) { this.rpc$ = new rxjs_1.ReplaySubject(1); const ping = params.ping ?? 15000; const codec = params.codec; const textEncoder = new TextEncoder(); this.channel = new channel_1.PersistentChannel(params.channel); this.channel.open$.pipe((0, operators_1.filter)((open) => open)).subscribe(() => { const close$ = this.channel.open$.pipe((0, operators_1.filter)((open) => !open)); const client = new StreamingRpcClient_1.StreamingRpcClient({ ...params.client, send: (messages) => { const encoded = codec.encode(messages, codec.req); this.channel.send$(encoded).subscribe(); }, }); this.channel.message$.pipe((0, operators_1.takeUntil)(close$)).subscribe((data) => { const encoded = typeof data === 'string' ? textEncoder.encode(data) : new Uint8Array(data); const messages = codec.decode(encoded, codec.res); client.onMessages((messages instanceof Array ? messages : [messages])); }); if (ping) { (0, rxjs_1.timer)(ping, ping) .pipe((0, operators_1.takeUntil)(close$)) .subscribe(() => { client.notify(params.pingMethod || '.ping', undefined); }); } if (this.rpc) this.rpc.disconnect(); this.rpc = client; this.rpc$.next(client); }); } call$(method, data) { return this.rpc$.pipe((0, operators_1.first)(), (0, operators_1.switchMap)((rpc) => rpc.call$(method, data)), (0, operators_1.share)()); } call(method, data) { return (0, rxjs_1.firstValueFrom)(this.call$(method, data)); } notify(method, data) { this.rpc$.subscribe((rpc) => rpc.notify(method, data)); } start() { this.channel.start(); } stop() { this.channel.stop(); if (this.rpc) this.rpc.stop(); } } exports.RpcPersistentClient = RpcPersistentClient; //# sourceMappingURL=RpcPersistentClient.js.map