From 62b06982ae6e02ed8422fb2834ad8b583a69e852 Mon Sep 17 00:00:00 2001 From: Sergey Krylov Date: Sat, 24 Jan 2026 14:30:19 +0300 Subject: [PATCH] feat: add redis --- src/infra/redis/redis.module.ts | 10 +++++ src/infra/redis/redis.service.ts | 64 ++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/infra/redis/redis.module.ts create mode 100644 src/infra/redis/redis.service.ts diff --git a/src/infra/redis/redis.module.ts b/src/infra/redis/redis.module.ts new file mode 100644 index 0000000..d47a2e2 --- /dev/null +++ b/src/infra/redis/redis.module.ts @@ -0,0 +1,10 @@ +import { Global, Module } from '@nestjs/common' + +import { RedisService } from './redis.service' + +@Global() +@Module({ + providers: [RedisService], + exports: [RedisService] +}) +export class RedisModule {} diff --git a/src/infra/redis/redis.service.ts b/src/infra/redis/redis.service.ts new file mode 100644 index 0000000..01fd42e --- /dev/null +++ b/src/infra/redis/redis.service.ts @@ -0,0 +1,64 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit +} from '@nestjs/common' +import { ConfigService } from '@nestjs/config' +import Redis from 'ioredis' + +@Injectable() +export class RedisService + extends Redis + implements OnModuleInit, OnModuleDestroy +{ + private readonly logger = new Logger(RedisService.name) + + public constructor(private readonly configService: ConfigService) { + super({ + username: configService.getOrThrow('REDIS_USERNAME'), + host: configService.getOrThrow('REDIS_HOST'), + port: configService.getOrThrow('REDIS_PORT'), + password: configService.getOrThrow('REDIS_PASSWORD'), + maxRetriesPerRequest: 5, + enableOfflineQueue: true + }) + } + + public onModuleInit() { + const start = Date.now() + + this.on('connect', () => { + this.logger.log('Redis connecting...') + }) + + this.on('ready', () => { + this.logger.log(`Redis connected in ${Date.now() - start}ms`) + }) + + this.on('error', e => { + this.logger.error('Redis connection error', { + error: e.message || e + }) + }) + + this.on('close', () => { + this.logger.warn('Redis connection closed') + }) + + this.on('reconnecting', () => { + this.logger.log('Redis reconnecting') + }) + } + + public async onModuleDestroy() { + this.logger.log('Redis disconnecting...') + + try { + await this.quit() + this.logger.log('Redis disconnected') + } catch (e) { + this.logger.error('Redis disconnecting error', e) + } + } +}