api.js 2.73 KB
const _ = require('lodash');
const Context = require('../framework/context');
const rp = require('request-promise');
const request = require('request');

const logger = global.yoho.logger;

const API_INTERNAL_ERROR = {
    code: 500,
    message: '服务器错误'
};

class Api extends Context {
    get(url, data, headers) {
        return this._request({
            url,
            qs: data,
            headers
        });
    }
    post(url, data, headers) {
        let defaultHeader = {
            'Content-Type': 'application/json'
        };

        return this._request({
            method: 'post',
            url,
            body: JSON.stringify(data),
            headers: Object.assign(defaultHeader, headers)
        });
    }
    upload(url, formData, headers) {
        let defaultHeader = {
            'Content-Type': 'application/json'
        };

        return this._request({
            method: 'post',
            url,
            formData,
            headers: Object.assign(defaultHeader, headers)
        });
    }
    proxy(url, data, options) {
        let params = _.merge({
            url,
            headers: {
                'Content-Type': 'application/json'
            }
        }, options);

        if (options.method === 'get') {
            params.qs = data;
        } else {
            params.body = JSON.stringify(data);
        }

        return request(params, (error, response) => {
            if (!error) {
                if (response && /^20\d/.test(response.statusCode)) {
                    logger.info(`api call ${response.statusCode} [${response.request.method}] ${response.request.href} ${response.request.body}`); // eslint-disable-line
                } else {
                    let res = response.toJSON();

                    logger.error(`api call ${res.statusCode} [${res.request.method}] ${res.request.uri.href} ${res.body || ''}`); // eslint-disable-line
                }
            }
        });
    }
    _request(options) {
        options = Object.assign(options, {
            resolveWithFullResponse: true
        });
        return rp[options.method || 'get'](options).then(response => {
            let jsonBody = JSON.parse(response.body);
            let req = response.request;

            logger.info(`api call ${response.statusCode} [${req.method}] ${req.uri.href} ${req.body || ''}`);
            return jsonBody;
        }).catch(err => {
            if (err.statusCode) {
                logger.error(`api call ${err.statusCode} [${err.options.method}] 
                ${err.options.url} ${err.response.body || ''}`);
            } else {
                logger.error(`api call ${err}`);
            }
            return Promise.reject(API_INTERNAL_ERROR);
        });
    }
}

module.exports = Api;