In this service i make reconnection to redis ```ts
@Injectable()
export class RedisService {
constructor(
@Inject(AZURE_CREDENTIALS)
private readonly azureCredentials: DefaultAzureCredential,
@Inject(REDIS_CLIENT)
private readonly redisClient: RedisClientType,
private readonly configService: ConfigService,
) {}
private accessTokenCache: AccessToken | undefined = undefined;
private expireInMinutes: number = 0;
private readonly logger = new Logger(RedisService.name);
@Cron(CronExpression.EVERY_MINUTE)
private async updateToken() {
//Cannot have negative expire in
if (this.expireInMinutes < 0) {
throw new Error('Failed to update redis token');
}
// You can get new token when current one expire time is less than 10 minutes, in other case you get the same token
if (this.expireInMinutes >= 10) {
--this.expireInMinutes;
return void 0;
}
const accessToken = await getRedisAccessToken(this.azureCredentials);
// Return if get same token
if (this.accessTokenCache?.token === accessToken.token) {
--this.expireInMinutes;
return void 0;
}
await this.redisClient
.auth({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
})
.catch((error) => {
this.logger.error(error, error.stack);
throw new InternalServerErrorException();
});
this.accessTokenCache = accessToken;
this.expireInMinutes = this.calculateTokenExpiryMinutes(accessToken);
return void 0;
}
//Method that calculate the approximate token expiration in minutes
private calculateTokenExpiryMinutes(accessToken: AccessToken): number {
const now = Date.now();
const expiresTimestamp = accessToken.expiresOnTimestamp;
const timeRemainingMs = expiresTimestamp - now;
const minutesRemaining = Math.floor(timeRemainingMs / (1000 * 60));
return minutesRemaining > 0 ? minutesRemaining : 0;
}
}