import { Injectable, Logger } from '@nestjs/common'; import { DataSource } from 'typeorm'; import { ConfigService } from '@nestjs/config'; import Redis from 'ioredis'; import type { HealthCheckResponseDto } from '@nick-tracker/shared-types'; @Injectable() export class HealthService { private readonly logger = new Logger(HealthService.name); private redis: Redis | null = null; constructor( private readonly dataSource: DataSource, private readonly configService: ConfigService, ) { this.initRedis(); } private initRedis() { const redisUrl = this.configService.get('REDIS_URL'); if (redisUrl) { try { this.redis = new Redis(redisUrl); } catch (error) { this.logger.warn('Failed to connect to Redis:', error); } } } async check(): Promise { const dbStatus = await this.checkDatabase(); const redisStatus = await this.checkRedis(); return { status: dbStatus === 'connected' && redisStatus === 'connected' ? 'ok' : 'error', database: dbStatus, redis: redisStatus, }; } private async checkDatabase(): Promise<'connected' | 'disconnected'> { try { if (this.dataSource.isInitialized) { await this.dataSource.query('SELECT 1'); return 'connected'; } return 'disconnected'; } catch (error) { this.logger.warn('Database health check failed:', error); return 'disconnected'; } } private async checkRedis(): Promise<'connected' | 'disconnected'> { if (!this.redis) { return 'disconnected'; } try { const result = await this.redis.ping(); return result === 'PONG' ? 'connected' : 'disconnected'; } catch (error) { this.logger.warn('Redis health check failed:', error); return 'disconnected'; } } }