UNPKG

@boringnode/transmit

Version:

A framework agnostic Server-Sent-Event library

110 lines (109 loc) 2.75 kB
/* * @boringnode/transmit * * @license MIT * @copyright BoringNode */ import matchit from 'matchit'; export class Storage { /** * Channels subscribed to a given stream */ #subscriptions = new Map(); /** * Channels subscribed to a given Stream UID */ #channelsByUid = new Map(); /** * Secured channels definition */ #securedChannelsDefinition = []; /** * Secure a channel */ secure(channel) { const encodedDefinition = matchit.parse(channel); this.#securedChannelsDefinition.push(encodedDefinition); } /** * Check if a channel is secured and return the matched channel */ getSecuredChannelDefinition(channel) { const matchedChannel = matchit.match(channel, this.#securedChannelsDefinition); if (matchedChannel.length > 0) { const params = matchit.exec(channel, matchedChannel); return { params, channel: matchedChannel[0].old }; } } /** * Get the number of secured channels */ getSecuredChannelCount() { return this.#securedChannelsDefinition.length; } /** * Get the number of streams */ getStreamCount() { return this.#subscriptions.size; } /** * Add a stream to the storage */ add(stream) { const channels = new Set(); this.#subscriptions.set(stream, channels); this.#channelsByUid.set(stream.getUid(), channels); } /** * Remove a stream from the storage */ remove(stream) { this.#subscriptions.delete(stream); this.#channelsByUid.delete(stream.getUid()); } /** * Add a channel to a stream */ subscribe(uid, channel) { const channels = this.#channelsByUid.get(uid); if (!channels) return false; channels.add(channel); return true; } /** * Remove a channel from a stream */ unsubscribe(uid, channel) { const channels = this.#channelsByUid.get(uid); if (!channels) return false; channels.delete(channel); return true; } /** * Find all subscribers to a channel */ findByChannel(channel) { const subscribers = new Set(); for (const [stream, streamChannels] of this.#subscriptions) { if (streamChannels.has(channel)) { subscribers.add(stream); } } return subscribers; } /** * Get channels for a given client */ getChannelByClient(uid) { return this.#channelsByUid.get(uid); } /** * Get all subscribers */ getAllSubscribers() { return this.#subscriptions; } }