import { Logger, Module } from '@nestjs/common'; import { createClient } from 'redis'; import { SecretModule } from '../secret/secret.module'; import { SecretService } from '../secret/secret.service'; import { GARNET_CLIENT } from './garnet.constants'; import { GarnetService, type GarnetRedisClient } from './garnet.service'; function normalizeGarnetUrl(endpoint: string): string { const trimmed = endpoint.trim(); if (!trimmed) { throw new Error('GARNET_ENDPOINT cannot be empty'); } if (/^redis(s)?:\/\//iu.test(trimmed)) { return trimmed; } return `redis://${trimmed}`; } @Module({ imports: [SecretModule], providers: [ { provide: GARNET_CLIENT, inject: [SecretService], useFactory: async ( secretService: SecretService, ): Promise => { await secretService.ready(); const [endpoint, username, password] = await Promise.all([ secretService.get('GARNET_ENDPOINT'), secretService.get('GARNET_USERID'), secretService.get('GARNET_PASSWORD'), ]); const logger = new Logger('GarnetClient'); const client = createClient({ url: normalizeGarnetUrl(endpoint), username, password, }); client.on('error', (error) => { logger.error(`Garnet client error: ${error?.message ?? error}`); }); await client.connect(); logger.log('Garnet connected'); return client; }, }, GarnetService, ], exports: [GarnetService, GARNET_CLIENT], }) export class GarnetModule {}