@synet/realtime
Version:
Realtime Communication server/client implementations
73 lines (72 loc) • 2.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketRealtimeProvider = void 0;
const websocket_channel_1 = require("./websocket-channel");
/**
* WebSocket-based implementation of RealtimeProvider
*/
class WebSocketRealtimeProvider {
constructor(baseUrl, options = {}) {
this.baseUrl = baseUrl;
this.options = options;
this.channels = new Map();
}
createChannel(topic, options = {}) {
// Create WebSocket URL with topic
const wsUrl = this.getWebSocketUrl(topic, options);
// Create the channel
const channel = new websocket_channel_1.WebSocketRealtimeChannel(wsUrl, {
...options,
reconnect: this.options.reconnect ?? options.reconnect,
authToken: this.options.authToken ?? options.authToken,
...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);
}
getChannels() {
return Array.from(this.channels.values());
}
async disconnect() {
const closePromises = Array.from(this.channels.values()).map((channel) => channel.close());
await Promise.all(closePromises);
this.channels.clear();
}
getWebSocketUrl(topic, options) {
const url = new URL(this.baseUrl);
// Add topic as path or query param
if (this.options.transportOptions?.topicInPath) {
url.pathname = `/${topic}${url.pathname}`;
}
else {
url.searchParams.append("topic", topic);
}
// Add auth token if provided
if (options.authToken) {
url.searchParams.append("token", options.authToken);
}
// Convert http(s) to ws(s)
if (url.protocol === "http:") {
url.protocol = "ws:";
}
else if (url.protocol === "https:") {
url.protocol = "wss:";
}
return url.toString();
}
}
exports.WebSocketRealtimeProvider = WebSocketRealtimeProvider;