All files / redis-client redis.service.ts

71.42% Statements 15/21
50% Branches 3/6
57.14% Functions 4/7
75% Lines 15/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 533x 3x           24x 24x   3x         3x     3x 3x       3x         24x               4x 4x 4x             4x 4x            
import { createClient } from 'redis';
export class RedisService {
  private static client;
 
  private constructor() {}
 
  static async init(client?: any): Promise<RedisService> {
    if (!client) {
      if (!RedisService.client) {
        // Create a new Redis client
        RedisService.client = createClient({
          url: process.env.REDIS_URL,
          password: process.env.REDIS_PASSWORD,
        });
 
        RedisService.client.on('error', (error) => {
          console.error('Redis error:', error);
        });
        RedisService.client.on('connect', () => console.log('Redis connected'));
        RedisService.client.on('reconnecting', () =>
          console.log('Redis reconnecting'),
        );
 
        await RedisService.client.connect();
      }
    } else E{
      RedisService.client = client;
    }
    return new RedisService();
  }
 
  public async set(
    key: string,
    value: any,
    expire: number = 3600 * 24 * 1,
  ): Promise<void> {
    try {
      const newList = typeof value === 'string' ? value : JSON.stringify(value);
      await RedisService.client.setEx(key, expire, newList);
    } catch (error) {
      console.log(error);
    }
  }
 
  public async get(key: string): Promise<null> {
    try {
      return await RedisService.client.get(key);
    } catch (error) {
      throw error;
    }
  }
}