Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

1.7 KB
Raw Blame
import type { ConnectionOptions as TlsOptions } from 'node:tls';

/**
 * A plain shape rather than ioredis's RedisOptions: BullMQ types its connection against its own
 * ioredis copy, and this object has to satisfy both.
 */
export interface RedisConnectionOptions {
  host: string;
  port: number;
  username?: string;
  password?: string;
  connectTimeout: number;
  tls?: TlsOptions;
}

/** Default REDIS_CONNECT_TIMEOUT_MS, also the producer's first-connect wait when that is set to 0. */
export const DEFAULT_REDIS_CONNECT_TIMEOUT_MS = 5000;

/**
 * The connection fields every Redis client shares: the cache, the throttler store, the BullMQ
 * producer and workers, and the WebSocket fan-out pair. Each caller spreads this and adds only its
 * role-specific behaviour (offline queue, retry strategy, database index).
 *
 * Reads process.env directly, not ConfigService: the @Processor decorators and the WebSocket adapter
 * evaluate it before the DI container exists. load-env has already merged .env and
 * data/.env.generated by then. REDIS_TLS=true connects over TLS with Node's default CA store (add a
 * private CA with NODE_EXTRA_CA_CERTS in the launch environment; Node reads it only at startup, so
 * .env cannot supply it).
 */
export function redisConnectionOptions(): RedisConnectionOptions {
  return {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT || '6379', 10),
    username: process.env.REDIS_USERNAME,
    password: process.env.REDIS_PASSWORD,
    connectTimeout: parseInt(process.env.REDIS_CONNECT_TIMEOUT_MS || String(DEFAULT_REDIS_CONNECT_TIMEOUT_MS), 10),
    ...(process.env.REDIS_TLS === 'true' ? { tls: {} } : {}),
  };
}