refactor(core): Simplify subscriber handler setters (#10896)

This commit is contained in:
Iván Ovejero
2024-09-23 14:14:00 +02:00
committed by GitHub
parent 23c09eae42
commit 5c171c4bf0
8 changed files with 170 additions and 167 deletions

View File

@@ -5,7 +5,7 @@ import config from '@/config';
import { Logger } from '@/logger';
import { RedisClientService } from '@/services/redis-client.service';
import type { ScalingPubSubChannel } from './pubsub.types';
import type { PubSubHandlerFn, PubSubChannel } from './pubsub.types';
/**
* Responsible for subscribing to the pubsub channels used by scaling mode.
@@ -14,6 +14,8 @@ import type { ScalingPubSubChannel } from './pubsub.types';
export class Subscriber {
private readonly client: SingleNodeClient | MultiNodeClient;
private readonly handlers: Map<PubSubChannel, PubSubHandlerFn> = new Map();
// #region Lifecycle
constructor(
@@ -26,6 +28,10 @@ export class Subscriber {
this.client = this.redisClientService.createClient({ type: 'subscriber(n8n)' });
this.client.on('error', (error) => this.logger.error(error.message));
this.client.on('message', (channel: PubSubChannel, message) => {
this.handlers.get(channel)?.(message);
});
}
getClient() {
@@ -41,7 +47,7 @@ export class Subscriber {
// #region Subscribing
async subscribe(channel: ScalingPubSubChannel) {
async subscribe(channel: PubSubChannel) {
await this.client.subscribe(channel, (error) => {
if (error) {
this.logger.error('Failed to subscribe to channel', { channel, cause: error });
@@ -52,8 +58,9 @@ export class Subscriber {
});
}
addMessageHandler(handlerFn: (channel: string, msg: string) => void) {
this.client.on('message', handlerFn);
/** Set the message handler function for a channel. */
setMessageHandler(channel: PubSubChannel, handlerFn: PubSubHandlerFn) {
this.handlers.set(channel, handlerFn);
}
// #endregion