product_cache.js 2.93 KB
/**
 *
 * @author: chenfeng<feng.chen@yoho.cn>
 * @date: 16/10/20
 */

import Model from './model';
import rp from 'request-promise';
import ws from '../../lib/ws';

class ProductCache extends Model{
    constructor() {
        super('product_cache');
    }
    async removePriceCache(list) {
        let self = this;
        let apis = await self.findAll();

        if (!apis.length) {
            return;
        }
        let url = apis[0].priceCacheApi;
        self._broadcast(`开始提交:批量变价`);
        await self._batchPost(list, url);
    }
    async removeProductCache(list) {
        let self = this;
        let apis = await self.findAll();

        if (!apis.length) {
            return;
        }
        let url = apis[0].productCacheApi;
        self._broadcast(`开始提交:其它批量`);
        await self._batchPost(list, url);
    }
    async _batchPost(list, url) {
        let self = this;
        let interval = 50;
        return new Promise(async (resolve, reject) => {
            let tick = parseInt(list.length / interval, 10) + (list.length % interval > 0 ? 1 : 0);
            let post = async (i, len) => {
                if (i < len) {
                    let limit = list.length > (i + 1) * interval ? (i + 1) * interval : list.length;
                    let datas = list.slice(i * interval, limit);
                    try {
                        await self._postApi(datas, url);
                        self._broadcast(`进度:${limit}/${list.length}`)
                    } catch(err) {
                        self._broadcast(`错误:${err.message}`)
                    }
                    setTimeout(async () => {
                        await post(++i, tick);
                    }, 500);
                } else {
                    self._broadcast(`提交完成!`);
                    resolve();
                }
            }
            await post(0, tick);
        });
    }
    async _postApi(data, url) {
        return new Promise((resolve, reject) => {
            rp({
                method: 'POST',
                uri: url,
                body: data,
                json: true
            })
            .then(function (res) {
                res.code === 200 ? resolve(res) : reject(res);
            })
            .catch(function (err) {
                console.log(err.response.body);
                reject(err.response.body)
            });
        })
        
    }
    _broadcast(message) {
        console.log(message)
        ws.broadcast(`/product_cache/log`, {
            message: message
        });
    }
    async init() {
        let count = await this.count({});

        if (count === 0) {
            await this.insert({
                priceCacheApi: 'http://service-test3.yohops.com:9999/erp/clear/batch/productPriceCache',
                productCacheApi: 'http://service-test3.yohops.com:9999/erp/clear/batch/productCache'
            });
        }
    }
}
export default ProductCache;