api.js 2.4 KB
/**
 * 接口公共访问方法
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/3/28
 */
'use strict';
var rp = require('request-promise'),
    _ = require('lodash');

var errUtil = require('../util/error');
var sign = require('./sign');

var API_CONFIG = {
    API_URL: 'http://testapi.yoho.cn:28078',
    SERVICE_URL: 'http://testservice.yoho.cn:28077'
};

if (process.env.NODE_ENV === 'production') {

    // 正式环境接口地址
    API_CONFIG = {
        API_URL: 'http://apih5.yoho.cn/',
        SERVICE_URL: 'http://serviceh5.yoho.cn/'
    };
}

class API {

    // var api = new API(); 默认调用新版接口
    // var api = new API('SERVICE_URL'); 服务调用方法

    constructor(type) {
        this.type = type || 'API_URL';
        this.headers = {
            'User-Agent': 'YOHO WEB NODE'
        };
        this.timeout = 5000;
        this.server = API_CONFIG[this.type];
        this.data = {};

        if (this.type === 'API_URL') {
            this.data.v = 7;
        }
    }

    get(url, data) {
        data = Object.assign(this.data, data);

        if (this.type === 'API_URL') {
            data = sign.apiSign(data);
        }

        return rp({
            url: `${this.server}${url}`,
            headers: this.headers,
            timeout: this.timeout,
            qs: data
        }).catch(errUtil.apiError);
    }

    /**
     * multi get
     * @params: urls => Array[Object[url[string], data[object]]]
     */
    multiGet(urls) {
        var rps = [],
            self = this;

        _.forEach(urls, function(el) {
            el.data = Object.assign(self.data, el.data);

            if (self.type === 'API_URL') {
                el.data = sign.apiSign(el.data);
            }

            rps.push(rp({
                url: `${self.server}${el.url}`,
                headers: self.headers,
                timeout: self.timeout,
                qs: el.data
            }));
        });

        return Promise.all(rps).then((d) => {
            return d;
        }).catch(errUtil.apiError);
    }

    post(url, data) {
        data = Object.assign(this.data, data);

        if (this.type === 'API_URL') {
            data = sign.apiSign(data);
        }

        return rp({
            url: `${this.server}${url}`,
            method: 'post',
            headers: this.headers,
            timeout: this.timeout,
            form: data
        }).catch(errUtil.apiError);
    }
}

module.exports = API;