Skip to content

Instantly share code, notes, and snippets.

@sonthanhdan
Created May 8, 2024 17:23
Show Gist options
  • Save sonthanhdan/61b3ff28c20d8707de2fd56985bc38de to your computer and use it in GitHub Desktop.
Save sonthanhdan/61b3ff28c20d8707de2fd56985bc38de to your computer and use it in GitHub Desktop.
import Redis from 'ioredis';
import { inject, injectable } from 'tsyringe';
import { Logger } from '@aws-lambda-powertools/logger';
import env from '@/configs/be-config';
@injectable()
export class CacheService {
private redis: Redis | undefined;
constructor(
@inject(Logger)
private readonly logger: Logger,
) {
try {
this.redis = new Redis({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASS,
db: process.env.REDIS_DB,
// connectTimeout: 100,
maxRetriesPerRequest: 1,
maxLoadingRetryTime: 100,
retryStrategy: (times) => Math.min(times * 10, 100),
});
this.redis.on('error', (error) => logger.error('redis error', { error }));
this.redis.on('connect', () => logger.info('redis connected'));
} catch (error) {
this.logger.error('Error on connect to Redis', { error });
this.redis = undefined;
}
}
private async reconnect() {
if (this.redis?.status === 'end') await this.redis.connect();
}
get isReady(): boolean {
return !!this.redis && this.redis.status === 'ready';
}
async set(key: string, value: any, expiration: number = 3600): Promise<string | number> {
if (!this.isReady) {
return '';
}
try {
await this.reconnect();
if (expiration === 0) return await this.redis!.setnx(key, JSON.stringify(value));
return await this.redis!.set(key, JSON.stringify(value), 'EX', expiration);
} catch (error) {
this.logger.error('Error on set cache', { error });
return '';
}
}
async get<T>(key: string): Promise<T | null> {
if (!this.isReady) {
return null;
}
try {
await this.reconnect();
const value = await this.redis!.get(key);
return value ? JSON.parse(value) : null;
} catch (error) {
this.logger.error('Error on get cache', { error });
return null;
}
}
async delete(key: string): Promise<number> {
if (!this.isReady) {
return 0;
}
try {
await this.reconnect();
return await this.redis!.del(key);
} catch (error) {
this.logger.error('Error on delete cache', { error });
return 0;
}
}
async close(): Promise<void> {
if (!this.isReady) {
return;
}
await this.redis!.quit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment