Skip to content

RedisConnectionFactory

Overview

RedisConnectionFactory is a static factory class that creates Redis connections in either single-node or cluster mode. It abstracts the differences between RedisHelper (single) and RedisClusterHelper (cluster) behind the common DefaultRedisHelper interface from IGNIS, allowing downstream code to work with either mode transparently.

PropertyValue
Sourcepackages/core/src/helpers/redis/redis-connection.factory.ts
ExtendsBaseHelper (from @venizia/ignis)
ReturnsDefaultRedisHelper (common interface for RedisHelper and RedisClusterHelper)

API

RedisConnectionFactory.create()

Creates a Redis connection based on the provided mode.

typescript
static create(opts: TRedisConnectionOptions): DefaultRedisHelper
ParameterTypeRequiredDescription
optsTRedisConnectionOptionsYesConnection options (single or cluster)

Returns: DefaultRedisHelper -- either a RedisHelper or RedisClusterHelper instance.

Throws: Error if an invalid mode is provided.

RedisConnectionFactory.parseClusterNodes()

Parses a comma-separated string of host:port pairs into an array of node objects. Intended for reading cluster node lists from environment variables.

typescript
static parseClusterNodes(opts: { raw: string }): Array<{ host: string; port: number }>
ParameterTypeRequiredDescription
opts.rawstringYesComma-separated string, e.g. "node1:6379,node2:6380,node3:6381"

Returns: Array of { host, port } objects. Defaults port to 6379 if parsing fails.

Type Interfaces

IRedisConnectionSingleOptions

Options for creating a single-node Redis connection.

typescript
interface IRedisConnectionSingleOptions {
  mode?: typeof RedisModes.SINGLE;  // 'single' (default when omitted)
  name: string;
  host?: string;        // Default: 'localhost'
  port?: number;        // Default: 6379
  password?: string;
  database?: number;    // Default: 0
  maxRetry?: number;    // Default: 5
  autoConnect?: boolean; // Default: false
}
FieldTypeDefaultDescription
mode'single''single'Connection mode identifier
namestring--Connection name for logging and identification
hoststring'localhost'Redis server hostname
portnumber6379Redis server port
passwordstring--Redis authentication password
databasenumber0Redis database index
maxRetrynumber5Maximum reconnection attempts
autoConnectbooleanfalseConnect immediately on creation

IRedisConnectionClusterOptions

Options for creating a Redis cluster connection.

typescript
interface IRedisConnectionClusterOptions {
  mode: typeof RedisModes.CLUSTER;  // 'cluster' (required)
  name: string;
  nodes: Array<{ host: string; port: number }>;
  password?: string;
}
FieldTypeDefaultDescription
mode'cluster'--Must be 'cluster'
namestring--Connection name for logging and identification
nodesArray<{ host, port }>--List of cluster seed nodes
passwordstring--Redis authentication password (applied to all nodes)

TRedisConnectionOptions

Union type of both option interfaces:

typescript
type TRedisConnectionOptions = IRedisConnectionSingleOptions | IRedisConnectionClusterOptions;

Behavior by Mode

Single Mode

Creates a RedisHelper instance with the provided options. This is the default when mode is omitted.

typescript
const redis = RedisConnectionFactory.create({
  name: 'my-cache-redis',
  host: 'localhost',
  port: 6379,
  database: 0,
  maxRetry: 5,
});

Internally produces:

typescript
new RedisHelper({
  name: 'my-cache-redis',
  host: 'localhost',
  port: 6379,
  password: undefined,
  database: 0,
  maxRetry: 5,
  autoConnect: false,
});

Cluster Mode

Creates a RedisClusterHelper instance with sharded subscribers enabled, lazy connection, and offline queue support.

typescript
const redis = RedisConnectionFactory.create({
  mode: 'cluster',
  name: 'my-cache-cluster',
  nodes: [
    { host: 'node1', port: 6379 },
    { host: 'node2', port: 6379 },
    { host: 'node3', port: 6379 },
  ],
  password: 'secret',
});

Internally produces:

typescript
new RedisClusterHelper({
  name: 'my-cache-cluster',
  nodes: [
    { host: 'node1', port: 6379 },
    { host: 'node2', port: 6379 },
    { host: 'node3', port: 6379 },
  ],
  clusterOptions: {
    redisOptions: { password: 'secret' },
    shardedSubscribers: true,
    lazyConnect: true,
    enableOfflineQueue: true,
  },
});

Cluster Mode Options

Cluster OptionValueDescription
shardedSubscriberstrueUses sharded pub/sub for Redis 7+ cluster subscriptions
lazyConnecttrueDoes not connect until the first command is issued
enableOfflineQueuetrueQueues commands while the connection is being established

Usage in Downstream Packages

Seven packages use RedisConnectionFactory to create WebSocket emitter connections:

Typical Component Usage

The pattern used by every package's ApplicationWebSocketComponent:

typescript
import { EnvironmentKeys, RedisConnectionFactory, RedisModes } from '@nx/core';
import { applicationEnvironment, WebSocketEmitter } from '@venizia/ignis';

export class ApplicationWebSocketComponent extends BaseComponent {
  override async binding(): Promise<void> {
    const mode =
      applicationEnvironment.get<string>(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_MODE) ??
      RedisModes.SINGLE;

    const redis =
      mode === RedisModes.CLUSTER
        ? this._createClusterRedis()
        : this._createSingleRedis();

    const emitter = new WebSocketEmitter({
      identifier: 'sale-ws-emitter',
      redisConnection: redis,
    });

    this.application.bind({ key: MyBindingKeys.WEBSOCKET_EMITTER }).toValue(emitter);
    this.application.service(MySocketEventService);
  }

  private _createSingleRedis() {
    return RedisConnectionFactory.create({
      mode: 'single',
      name: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_IDENTIFIER)
        ?? 'my-ws-redis',
      host: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_HOST)
        ?? 'localhost',
      port: int(applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_PORT))
        ?? 6379,
      password: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_PASSWORD),
      database: int(applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_DB))
        ?? 0,
      maxRetry: int(applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_MAX_RETRY))
        ?? 5,
    });
  }

  private _createClusterRedis() {
    const clusterNodesStr = applicationEnvironment.get<string>(
      EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_CLUSTER_NODES,
    );

    if (!clusterNodesStr) {
      throw getError({ message: 'Missing cluster nodes env var' });
    }

    return RedisConnectionFactory.create({
      mode: 'cluster',
      name: applicationEnvironment.get(
        EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_CLUSTER_IDENTIFIER,
      ) ?? 'my-ws-redis-cluster',
      nodes: RedisConnectionFactory.parseClusterNodes({ raw: clusterNodesStr }),
      password: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_PASSWORD),
    });
  }
}

Environment Variables

VariableUsed ForExample
APP_ENV_WEBSOCKET_REDIS_MODESelect single or clustersingle
APP_ENV_WEBSOCKET_REDIS_HOSTSingle mode hostnamelocalhost
APP_ENV_WEBSOCKET_REDIS_PORTSingle mode port6379
APP_ENV_WEBSOCKET_REDIS_PASSWORDAuthentication (both modes)secret
APP_ENV_WEBSOCKET_REDIS_DBSingle mode database index0
APP_ENV_WEBSOCKET_REDIS_MAX_RETRYSingle mode retry count5
APP_ENV_WEBSOCKET_REDIS_CLUSTER_NODESCluster mode node listnode1:6379,node2:6379

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.