Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.8 kB
2
Indexable
Never
import { logger } from 'app/utils/logger';
import Redis from 'ioredis';
import { Service } from 'typedi';

@Service()
class CacheService {
  private _client: Redis;
  private _keepAlive: any;
  private _connected = false;
  private _ready = false;
  private _error: any = undefined;
  //
  constructor() {
    void this.initialize();
  }

  public getClient(): any {
    return this._client;
  }
  public setClient(client: Redis): void {
    this._client = client;
  }
  public getKeepAlive(): any {
    return this._keepAlive;
  }
  public setKeepAlive(keepAlive: any): void {
    this._keepAlive = keepAlive;
  }
  public getConnected(): boolean {
    return this._connected;
  }
  public setConnected(connected: boolean): void {
    this._connected = connected;
  }
  public getState(): boolean {
    return this._ready;
  }
  public setState(connected: boolean): void {
    this._ready = connected;
  }

  isConnected(): boolean {
    return this.getConnected();
  }

  isReady(): boolean {
    return this.getState();
  }
  public getError(): any {
    return this._error;
  }
  public setError(error: any): void {
    this._error = error;
  }
  hasError(): boolean {
    return this.getError() === undefined;
  }

  initialize = () => {
    const { REDIS_HOST, REDIS_PORT } = process.env;
    const host = REDIS_HOST;
    const port = parseInt(REDIS_PORT.replaceAll("'", ''));
    this.setClient(
      new Redis({
        host: host,
        port: port,
        connectTimeout: 2500,
        maxRetriesPerRequest: 2,
      })
    );
    //
    this.getClient().on('connect', () => {
      this.setConnected(true);
      this.setError(null);
      //
      logger.info('Cache connected.');
    });

    this.getClient().on('ready', () => {
      this.setState(true);
      //
      logger.info('Cache is ready.');
    });

    this.getClient().on('end', () => {
      this.setConnected(false);
      this.setState(false);
      //
      logger.error('Cache is stopped.');
    });

    this.getClient().on('error', (err: Error) => {
      this.setConnected(false);
      this.setState(false);
      this.setError(err);
      //
      logger.error('Cache error : ' + err.stack);
    });
  };

  async getDataOnRedis(data: any) {
    try {
      let dataOnRedis = await this.getClient().get(data.key);
      return dataOnRedis;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async setDataOnRedis(data: any) {
    try {
      let addData = await this.getClient().set(data.key, data.value);
      return addData;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async pushOnRedis(data: any) {
    try {
      let pushDataOnRedis = await this.getClient().rpush(data.key, data.value);
      return pushDataOnRedis;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async deleteDataOnRedis(data: any) {
    try {
      let deletedData = await this.getClient().del(data.key);
      return deletedData;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async existsOnRedis(data: any) {
    try {
      let redisKeyExists = await this.getClient().exists(data.key);
      return redisKeyExists;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async getDataLengthOnRedis(data: any) {
    try {
      let redisDataLength = await this.getClient().llen(data.key);
      return redisDataLength;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async getDataLengthRangeOnRedis(data: any) {
    try {
      let redisDataLengthRange = await this.getClient().lrange(data.key, data.start, data.listLength);
      return redisDataLengthRange;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async setListDataOnRedis(data: any) {
    try {
      let setData = await this.getClient().lset(data.key, data.index, data.value);
      return setData;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async removeDataOnRedis(data: any) {
    try {
      let removedData = await this.getClient().lrem(data.key, data.start, data.listLength);
      return removedData;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async setDataOnRedisWithExpire(data: any, expireTime: number) {
    try {
      //expireTime in sec
      let addData = await this.getClient().set(data.key, data.value, 'EX', expireTime);
      return addData;
    } catch (err: any) {
      throw new Error(err);
    }
  }

  async scanStream(key: any) {
    try {
      const stream = await this.getClient().scanStream({
        // only returns keys following the pattern of `cloudbedsSync:*`
        match: key,
        // returns approximately 100 elements per call
        count: 100,
      });
      return stream;
    } catch (err: any) {
      throw new Error(err);
    }
  }
}

export default CacheService;
Leave a Comment