()
| 9 | * @returns Result containing RedisClient or RedisConfigurationError if REDIS_URL is not set |
| 10 | */ |
| 11 | export async function createRedisClientFromEnv(): Promise<Result<RedisClient, CacheError>> { |
| 12 | const url = process.env.REDIS_URL; |
| 13 | if (!url) { |
| 14 | logger.error("REDIS_URL is required to create the Redis client"); |
| 15 | return err({ |
| 16 | code: ErrorCode.RedisConfigurationError, |
| 17 | }); |
| 18 | } |
| 19 | |
| 20 | const client = createClient({ |
| 21 | url, |
| 22 | socket: { |
| 23 | connectTimeout: 3000, |
| 24 | }, |
| 25 | }); |
| 26 | |
| 27 | client.on("error", (error) => { |
| 28 | logger.error(error, "Redis client error"); |
| 29 | try { |
| 30 | resetCacheFactory(); |
| 31 | client.destroy(); |
| 32 | } catch (e) { |
| 33 | logger.error(e, "Error destroying Redis client"); |
| 34 | } |
| 35 | }); |
| 36 | |
| 37 | client.on("connect", () => { |
| 38 | logger.info("Redis client connected"); |
| 39 | }); |
| 40 | |
| 41 | client.on("ready", () => { |
| 42 | logger.info("Redis client ready"); |
| 43 | }); |
| 44 | |
| 45 | client.on("end", () => { |
| 46 | logger.info("Redis client disconnected"); |
| 47 | }); |
| 48 | |
| 49 | try { |
| 50 | await client.connect(); |
| 51 | return ok(client as RedisClient); |
| 52 | } catch (error) { |
| 53 | logger.error(error, "Redis client connection failed"); |
| 54 | return err({ code: ErrorCode.RedisConnectionError }); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // Global singleton with globalThis for cross-module sharing |
| 59 | const globalForCache = globalThis as unknown as { |
no test coverage detected