import Redis from "ioredis"
* Creates a Redis connection based on the provided Redis URL.
* Supports both single Redis instances and Redis Sentinel configurations.
* const redis = redisFactory("redis://user:password@localhost:6379")
* const redisSentinel = redisFactory("redis+sentinel://user:password@localhost:26379/mymaster")
* @param {string} redisUrl - The Redis URL to connect to. Can be a single Redis instance or a Redis Sentinel instance.
* @returns {Redis} A Redis connection instance.
export const redisFactory = (redisUrl: string) => {
if (redisUrl.startsWith("redis+sentinel://")) {
const [credentialsAndHost, masterSet] = redisUrl.split("//")[1].split("/")
let credentials: string | undefined
let hostInfo: string | undefined
let port: string | undefined
if (credentialsAndHost.includes("@")) {
;[credentials, hostInfo] = credentialsAndHost.split("@")
;[hostInfo, port] = credentialsAndHost.split(":")
let username: string | undefined
let password: string | undefined
if (credentials?.includes(":")) {
;[username, password] = credentials.split(":")
;[host, port] = hostInfo.split(":")
;[host, port] = credentialsAndHost.split(":")
return redisSentinelFactory(host, Number.parseInt(port), username, password, masterSet)
return new Redis(redisUrl)
* Creates a Redis connection using Sentinel configuration.
* @param {string} sentinelUrl - The URL of the Sentinel instance.
* @param {number} [port] - The port number of the Sentinel instance. Defaults to 26379 if not provided.
* @param {string} [username] - The username for authentication.
* @param {string} [password] - The password for authentication.
* @param {string} [setName="mymaster"] - The name of the Sentinel set.
* @returns {Redis} A Redis connection instance configured with Sentinel.
export const redisSentinelFactory = (
sentinels: [{ host: sentinelUrl, port: port ?? 26379 }],
...(password && { sentinelPassword: password }),
...(password && { password }),
...(username && { username }),