wheel-surf-redis.js 1.76 KB
const _ = require('lodash');

class ActWheelSurfRedis extends global.yoho.BaseModel {
  constructor(ctx) {
    super(ctx);
    this.redis = global.yoho.redis;
    this.client = this.redis.client;
  }
  getActConf(actId) {
    return this.client.hgetallAsync(`turntable:${actId}`).then(conf => {
      Object.keys(conf).forEach(key => {
        if (conf[key] && !_.isNaN(Number(conf[key]))) {
          conf[key] = Number(conf[key])
        }
      });
      return conf;
    });
  }
  setActConf(actId, confObj) {
    confObj.id = 1;
    return this.client.HMSET(`turntable:${actId}`, confObj);
  }
  getActPrize(actId, len = 7) {
    return this.client.lrangeAsync(`turntable:${actId}:prize`, 0, len)
      .then(async (prizes) => {
        let left = 0;
        for (let i = 0; i < prizes.length; i++) {
          prizes[i] =JSON.parse(prizes[i]);
          left = await this.client.getAsync(`turntable:${actId}:prize:${prizes[i].prize_idx}:stock`);
          prizes[i].total_left = +left;
        }
        return prizes;
      });
  }
  createActPrize(actId, prizesList) {
    prizesList = prizesList || [];

    let multi = this.client.multi();
    prizesList.map((prize, idx) => {
      prize.id = idx + 1;
      multi.lpush(`turntable:${actId}:prize`, JSON.stringify(prize));
      multi.set(`turntable:${actId}:prize:${prize.prize_idx}:stock`, prize.total_left);
    });
    return multi.execAsync();
  }
  updateActPrize(actId, prizesList) {
    prizesList = prizesList || [];

    let multi = this.client.multi();
    prizesList.map((prize, idx) => {
      multi.lset(`turntable:${actId}:prize`, idx, JSON.stringify(prize));
      multi.set(`turntable:${actId}:prize:${prize.prize_idx}:stock`, prize.total_left);
    });
    return multi.execAsync();
  }
}

module.exports = ActWheelSurfRedis;