UNPKG

@synet/realtime

Version:

Realtime Communication server/client implementations

78 lines (77 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NatsRealtimeProvider = void 0; const nats_channel_1 = require("./nats-channel"); /** * NATS-based implementation of RealtimeProvider */ class NatsRealtimeProvider { constructor(baseUrl, options = {}) { this.baseUrl = baseUrl; this.options = options; this.channels = new Map(); } /** * Create a channel for the specified topic */ createChannel(topic, options = {}) { // Create NATS URL with topic const natsUrl = this.getNatsUrl(topic, options); // Create the channel with merged options const channel = new nats_channel_1.NatsRealtimeChannel(natsUrl, { ...this.options, ...options, reconnect: this.options.reconnect ?? options.reconnect, authToken: this.options.authToken ?? options.authToken, transportOptions: { ...this.options.transportOptions, ...options.transportOptions, }, }); // Start connecting in background - doesn't wait for connection to complete channel.connect().catch((error) => { console.error(`Error connecting to channel ${topic}:`, error); }); // Store the channel this.channels.set(channel.id, channel); return channel; } /** * Remove a channel */ async removeChannel(channel) { // Close the channel await channel.close(); // Remove from our collection this.channels.delete(channel.id); } /** * Get all active channels */ getChannels() { return Array.from(this.channels.values()); } /** * Close all channels and clean up resources */ async disconnect() { const closePromises = Array.from(this.channels.values()).map((channel) => channel.close()); await Promise.all(closePromises); this.channels.clear(); } /** * Create a NATS URL with topic as query parameter */ getNatsUrl(topic, options) { // Start with the base URL const url = new URL(this.baseUrl); // Add topic as query param url.searchParams.append("topic", topic); // Add auth token if provided if (options.authToken || this.options.authToken) { url.searchParams.append("token", options.authToken || this.options.authToken || ""); } return url.toString(); } } exports.NatsRealtimeProvider = NatsRealtimeProvider;