37 lines
966 B
TypeScript
37 lines
966 B
TypeScript
/* eslint-disable no-console */
|
|
import envSchema from '@/config/schema/env';
|
|
import type { RedisOptions } from 'ioredis';
|
|
import { Redis } from 'ioredis';
|
|
|
|
const { REDIS_HOST, REDIS_PORT } = envSchema.parse(process.env);
|
|
|
|
export function createRedisInstance() {
|
|
try {
|
|
const options: RedisOptions = {
|
|
enableAutoPipelining: true,
|
|
host: REDIS_HOST,
|
|
lazyConnect: true,
|
|
maxRetriesPerRequest: 0,
|
|
port: REDIS_PORT,
|
|
retryStrategy: (times: number) => {
|
|
if (times > 3) {
|
|
throw new Error(`[Redis] Could not connect after ${times} attempts`);
|
|
}
|
|
|
|
return Math.min(times * 200, 1000);
|
|
},
|
|
showFriendlyErrorStack: true,
|
|
};
|
|
|
|
const redis = new Redis(options);
|
|
|
|
redis.on('error', (error: unknown) => {
|
|
console.warn('[Redis] Error connecting', error);
|
|
});
|
|
|
|
return redis;
|
|
} catch (error) {
|
|
throw new Error(`[Redis] Could not create a Redis instance. ${error}`);
|
|
}
|
|
}
|