const IORedis = require('ioredis');
const config = require('src/config/index.js');

class Redis extends IORedis {
  constructor() {
    let { prefix } = config.redis;
    const { host, port, password, db } = config.redis;
    if (prefix && !/:$/.test(prefix)) prefix += ':';
    super({
      host,
      port,
      password,
      db,
    });

    this.prefix = prefix;

    const self = this;
    // key pattern functions
    this.Key = {
      /**
       * SSO 登入暫存
       * @param {string} s state
       * @return {string}
       */
      ssoLoginCache: s => self.getKeyWithPrefix(`sso-login:${s}`),
    };
  }

  /**
   * combine key and prefix
   * @param {string} s
   * @return {string}
   */
  getKeyWithPrefix(s) {
    if (typeof s !== 'string') throw new Error('input key not a string');

    return `${this.prefix}${s}`;
  }
}

module.exports = new Redis();
