ssrDegradeModel.js 2.51 KB
const model = require('../../../lib/model');
const {client} = require('../../../lib/redis');
const ZookeeperModel = require('../../web/models/zookeeperModel');
const _ = require('lodash');

class SsrDegradeModel extends model {
    constructor(ctx) {
        super(ctx);        
    }
    async getApps() {
      const appsData = await client.getAsync('degradeSSRKeys');
      const apps = JSON.parse(appsData || '[]');

      return Promise.all(_.map(apps, this.getApp));
    }

    async getApp(app) {
      const zookeeperModel = new ZookeeperModel();
      const [degradeJson, isDegradeJson] = await Promise.all([
        client.getAsync(`${app}:degradessr`),
        client.getAsync(`${app}:degradessr:isdegrade`)]
      );
      const zkIsDegrade = await zookeeperModel.getPath(`/wap/webapp/${app}-degrade`);
      const degrades = JSON.parse(degradeJson || '[]');
      let isDegrade;

      if (isDegradeJson) {
        isDegrade = JSON.parse(isDegradeJson);

        _.forEach(degrades, d => {
          if (d.time === isDegrade.time && d.tick === isDegrade.tick) {
            d.status = true;
            d.maxTick = d.maxTick;
          }
        })
      }

      return {
        app,
        degrades,
        status: zkIsDegrade === 'true'
      };
    }
    async editApp(data) {
      const zookeeperModel = new ZookeeperModel();
      const appsData = await client.getAsync('degradeSSRKeys');
      const apps = JSON.parse(appsData || '[]');

      if (!apps.some(app => app === data.app)) {
        apps.push(data.app);
        client.setAsync('degradeSSRKeys', JSON.stringify(apps));
      }
      zookeeperModel.setPath(`/wap/webapp/${data.app}-degrade`, false);
      client.delAsync(`${data.app}:degradessr:isdegrade`);
      const degrades = _.map(data.degrades, d => {
        return {
          time: d.time,
          tick: d.tick,
          delay: d.delay
        }
      })
      return await client.setAsync(`${data.app}:degradessr`, JSON.stringify(degrades));
    }
    async deleteApp(data) {
      const zookeeperModel = new ZookeeperModel();
      const appsData = await client.getAsync('degradeSSRKeys');
      const apps = JSON.parse(appsData || '[]');
      const saveApps = apps.filter(app => app !== data.app);
      
      client.setAsync('degradeSSRKeys', JSON.stringify(saveApps));
      client.delAsync(`${data.app}:degradessr`);
      client.delAsync(`${data.app}:degradessr:isdegrade`);
      zookeeperModel.setPath(`/wap/webapp/${data.app}-degrade`, false);

      return true;
    }
}

module.exports = SsrDegradeModel;