const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
  constructor() {
    this.redisClient = system.getObject("util.redisClient");
    this.desc = this.desc();
    this.prefix = this.prefix();
    this.cacheCacheKeyPrefix = "s_sadd_appkeys:" + settings.appKey + "_cachekey";
    this.isdebug = this.isdebug();
  }
  isdebug() {
    return true;
  }
  desc() {
    throw new Error("子类需要定义desc方法，返回缓存描述");
  }
  prefix() {
    throw new Error("子类需要定义prefix方法，返回本缓存的前缀");
  }
  async cache(inputkey, val, ex, ...items) {
    const cachekey = this.prefix + inputkey;
    var cacheValue = await this.redisClient.get(cachekey);
    if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
      var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
      if (!objvalstr) {
        return null;
      }
      if (ex) {
        await this.redisClient.setWithEx(cachekey, objvalstr, ex);
      } else {
        await this.redisClient.set(cachekey, objvalstr);
      }
      //缓存当前应用所有的缓存key及其描述
      this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
      return JSON.parse(objvalstr);
    } else {
      return JSON.parse(cacheValue);
    }
  }
  async invalidate(inputkey) {
    const cachekey = this.prefix + inputkey;
    this.redisClient.delete(cachekey);
    return 0;
  }
  async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
    throw new Error("子类中实现构建缓存值的方法，返回字符串");
  }
}
module.exports = CacheBase;
