valkey-redis-eventbus
Version:
A lightweight event bus implementation using Redis (Valkey) for scalable inter-process communication in Node.js applications.
87 lines (86 loc) • 2.95 kB
TypeScript
import { RedisClientType } from "redis";
export declare class EventBus {
private static _eventBusInstances;
private readonly _pub;
private readonly _sub;
private readonly _name;
private readonly _prefix;
/**
* Private constructor for EventBus. Use EventBus.create() to instantiate.
* @param name Name of the EventBus instance
* @param prefix Prefix for Redis channels
* @param pub Redis client for publishing
* @param sub Redis client for subscribing
*/
private constructor();
/**
* Initializes the EventBus by subscribing to internal 'ping' events.
*/
private init;
/**
* Registers a callback for a specific event.
* @param event Event name to listen for
* @param callback Function to call when the event is received
*/
on<T>(event: string, callback: (payload: T) => void): Promise<void>;
/**
* Internal method to subscribe to an event channel.
* @param event Event name
* @param callback Callback to execute on event
* @param internalCall Whether this is an internal event
*/
private _on;
/**
* Emits an event with the given payload.
* @param event Event name
* @param payload Data to send
*/
emit<T>(event: string, payload: T): void;
/**
* Internal method to publish an event.
* @param event Event name
* @param payload Data to send
* @param internalCall Whether this is an internal event
*/
private _emit;
/**
* Pings all EventBus instances and waits for pong responses.
* @param timeout Timeout in ms to wait for responses
* @param minResponseCount Minimum number of responses required
* @returns Promise resolving to true if enough responses are received
*/
ping(timeout?: number, minResponseCount?: number): Promise<boolean>;
/**
* Cleans up the EventBus instance and closes Redis connections.
*/
destroy(): Promise<void>;
/**
* Returns true if both Redis clients are connected.
*/
get connected(): boolean;
/**
* Returns the channel name with prefix applied.
* @param channel Channel name
* @returns Prefixed channel name
*/
private getPrefixedChannelName;
/**
* Checks if the event name is reserved (internal use).
* @param event Event name
* @returns True if reserved
*/
private isReservedEventName;
/**
* Creates a new EventBus instance or returns an existing one.
* @param name Name of the EventBus instance
* @param clientOpts Redis client options
* @returns EventBus instance
*/
static create(name: string, clientOpts?: RedisClientType<any>["options"], prefix?: string): Promise<EventBus>;
/**
* Retrieves an EventBus instance by name.
* @param name Name of the EventBus instance
* @returns EventBus instance
*/
static getByName(name: string): EventBus;
}