cache.js 1.27 KB
/*
 * @Author: limin
 * @Date: 2019-11-21 14:32:51
 * @Last Modified by: limin
 * @Last Modified time: 2019-12-05 17:34:43
 */

"use strict";

const Service = require("egg").Service;

class CacheService extends Service {
  constructor(ctx) {
    super(ctx);
    this.session = ctx.session;
    this.ResponseCode = ctx.response.ResponseCode;
    this.ServerResponse = ctx.response.ServerResponse;
    this.helper = ctx.helper;
    this.PREFIX = ctx.helper.constant.PREFIX;
  }
  async set(key, value, ex = this.app.config.sys.user_cache_expires_time) {
    this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.json_stringify(value), "EX", ex));
  }

  async get(key, fnGetFromDB, ex) {
    if (this.app.redis) {
      var value = await this.app.redis.get(`${this.helper.constant.PREFIX}${key}`);
      if(value){
        value =this.helper.json_parser(value)
        return value
      }
    }
    if (fnGetFromDB) {
      var data = await fnGetFromDB();
      if( data && data.length ){
        const{ date } =data[0]
        const { today } =  await this.get(this.helper.constant.DATES)
        if(date.split(' ')[0] === today) {
          await this.set(key, data, ex);
        }
      }
      return data;
    }
    return null;
  }
}

module.exports = CacheService;