|
1 | 1 | import { Duration, Redacted } from 'effect';
|
| 2 | +import type { RedisOptions } from 'ioredis'; |
2 | 3 | import Redis from 'ioredis';
|
3 | 4 |
|
4 | 5 | import { serverEnvironment } from '~/.server/environment';
|
5 | 6 | import { LogFactory } from '~/.server/logging';
|
| 7 | +import { singleton } from '~/.server/utils/instance-registry'; |
6 | 8 |
|
7 | 9 | const log = LogFactory.getLogger(import.meta.url);
|
8 | 10 |
|
9 |
| -/** |
10 |
| - * A holder for our singleton redis client instance. |
11 |
| - */ |
12 |
| -const clientHolder: { client?: Redis } = {}; |
13 |
| - |
14 | 11 | /**
|
15 | 12 | * Retrieves the application's redis client instance.
|
16 | 13 | * If the client does not exist, it initializes a new one.
|
17 | 14 | */
|
18 |
| -export function getRedisClient() { |
19 |
| - return (clientHolder.client ??= createRedisClient()); |
20 |
| -} |
21 |
| - |
22 |
| -/** |
23 |
| - * Creates a new Redis client and sets up logging for connection and error events. |
24 |
| - */ |
25 |
| -function createRedisClient(): Redis { |
26 |
| - log.info('Creating new redis client'); |
| 15 | +export function getRedisClient(): Redis { |
| 16 | + return singleton('redisClient', () => { |
| 17 | + log.info('Creating new redis client'); |
27 | 18 |
|
28 |
| - const { REDIS_CONNECTION_TYPE, REDIS_HOST, REDIS_PORT } = serverEnvironment; |
| 19 | + const { REDIS_CONNECTION_TYPE, REDIS_HOST, REDIS_PORT } = serverEnvironment; |
29 | 20 |
|
30 |
| - return new Redis(getRedisConfig()) |
31 |
| - .on('connect', () => log.info('Connected to %s://%s:%s/', REDIS_CONNECTION_TYPE, REDIS_HOST, REDIS_PORT)) |
32 |
| - .on('error', (error) => log.error('Redis client error: %s', error.message)); |
| 21 | + return new Redis(getRedisConfig()) |
| 22 | + .on('connect', () => log.info('Connected to %s://%s:%s/', REDIS_CONNECTION_TYPE, REDIS_HOST, REDIS_PORT)) |
| 23 | + .on('error', (error) => log.error('Redis client error: %s', error.message)); |
| 24 | + }); |
33 | 25 | }
|
34 | 26 |
|
35 | 27 | /**
|
36 | 28 | * Constructs the configuration object for the Redis client based on the server environment.
|
37 | 29 | */
|
38 |
| -function getRedisConfig() { |
| 30 | +function getRedisConfig(): RedisOptions { |
39 | 31 | const {
|
40 | 32 | REDIS_COMMAND_TIMEOUT_SECONDS, //
|
41 | 33 | REDIS_HOST,
|
|
0 commit comments