index.js 2.09 KB
'use strict';

const ROOT_PATH = global.ROOT_PATH;
const _ = require('lodash');
const rp = require('request-promise');
const util = require(`${ROOT_PATH}/libs/util`);
const senUrl = 'http://data.zz.baidu.com/urls?appid=1583402501013173&token=K0L5PUhk1XOko81r&type=';

class XzhIndexModel extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
    }

    index() {
        // 新增
        return this.getLastArticleList({page: 1, limit: 100}).then(rdata => {
            rdata = _.get(rdata, 'data.artList', []);

            return this.sendData(rdata, 'realtime');
        });
    }

    sendDataHistory(page) {
        return util.sleep(3000).then(() => {
            return this.getLastArticleList({page: 1});
        }).then(rdata => {
            rdata = _.get(rdata, 'data.artList', []);

            if (rdata.length <= 0) {
                return false;
            }

            return this.sendData(rdata).then(result => {
                console.log(`sendDataHistory => result: ${JSON.stringify(result)}, page: ${page} `);
                return this.sendDataHistory(++page);
            });
        });
    }

    // 向百度发送数据
    sendData(data, type) {
        type = type || 'batch';

        data = _.map(data, item => {
            return `https://m.yohobuy.com/mip/guang/${item.articleId}.html`;
        });

        return rp({
            method: 'POST',
            uri: `${senUrl}${type}`,
            body: data.join('\n'),
            timeout: 8 * 1000
        }).then(result => {
            return JSON.parse(result || '{}');
        });
    }

    getLastArticleList(params) {
        params = _.assign({
            limit: 100,
            udid: 'seo_format_data'
        }, params);

        return this.get({
            url: '/guang/api/v2/article/getLastArticleList',
            data: params,
            param: {
                cache: 86400
            },
            api: global.yoho.ServiceAPI
        }).catch(e => {
            console.log(e.message);
            return {code: 400, data: {}, message: e.message};
        });
    }
}

module.exports = XzhIndexModel;