import { InternalServerErrorException } from '@nestjs/common';
import Redis from 'ioredis'

class RedisService {
  constructor(redisPort, redisHost) {
    if (RedisService.instance)
      return RedisService.instance

    this.redis = new Redis({
      port: redisPort,
      host: redisHost,
    });

    RedisService.instance = this

    Object.freeze(this)
  }

  async setex(key, expiry, value) {
    try {
      this.redis.setex(key, expiry, value);
    } catch (err) {
      throw new InternalServerErrorException(err)
    }
  }

  async set(key, value) {
    try {
      this.redis.set(key, value);
    } catch (err) {
      throw new InternalServerErrorException(err)
    }
  }

  async get(key) {
    try {
      return this.redis.get(key);
    } catch (err) {
      throw new InternalServerErrorException(err)
    }
  }
}

const redis = new RedisService(6379, 'localhost')

export default redis