-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalias.module.ts
More file actions
78 lines (71 loc) · 2.44 KB
/
alias.module.ts
File metadata and controls
78 lines (71 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Module, Global, Logger, OnModuleDestroy, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Redis from 'ioredis';
import { ALIAS_REDIS_CLIENT } from './alias.constants';
import { AliasService } from './alias.service';
const logger = new Logger('AliasRedisModule');
/**
* AliasModule
*
* Provides a dedicated ioredis connection to the external alias Redis instance.
* Kept separate from RedisModule (session store) so the two concerns never share
* a connection and can be configured / replaced independently.
*
* Key format stored by the dashboard:
* {ALIAS_REDIS_KEY_PREFIX}:{alias} → projectApiKey (plain string)
*/
@Global()
@Module({
providers: [
{
provide: ALIAS_REDIS_CLIENT,
useFactory: (configService: ConfigService): Redis => {
const client = new Redis({
host: configService.get<string>('ALIAS_REDIS_HOST', 'localhost'),
port: configService.get<number>('ALIAS_REDIS_PORT', 6379),
password: configService.get<string>('ALIAS_REDIS_PASSWORD') || undefined,
db: configService.get<number>('ALIAS_REDIS_DB', 0),
retryStrategy: (times: number) => {
if (times > 3) {
logger.error(`Alias Redis connection failed after ${times} attempts. Giving up.`);
return null;
}
const delay = Math.min(times * 500, 3000);
logger.warn(
`Alias Redis connection attempt ${times} failed. Retrying in ${delay}ms...`,
);
return delay;
},
lazyConnect: false,
});
client.on('connect', () => {
logger.log('Alias Redis client connected');
});
client.on('error', (err: Error) => {
logger.error(`Alias Redis client error: ${err.message}`);
});
client.on('close', () => {
logger.warn('Alias Redis client connection closed');
});
return client;
},
inject: [ConfigService],
},
AliasService,
],
exports: [AliasService],
})
export class AliasModule implements OnModuleDestroy {
constructor(
@Inject(ALIAS_REDIS_CLIENT)
private readonly redis: Redis,
) {}
async onModuleDestroy(): Promise<void> {
try {
await this.redis.quit();
logger.log('Alias Redis client disconnected gracefully');
} catch (err) {
logger.error(`Error disconnecting Alias Redis: ${(err as Error).message}`);
}
}
}