api.js 2.21 KB
const Context = require('./context');
const request = require('request');
const qs = require('querystring');
const _ = require('lodash');

const config = global.yoho.config;
const logger = global.yoho.logger;

const API_ERROR = {
    code: 0,
    message: '网络异常'
};
const API_INTERNAL_ERROR = {
    code: 500,
    message: '服务器错误'
};

class Api extends Context {
    constructor() {
        super();
    }
    get(url, data, headers) {
        this.logGet(url, data);
        return this.parse(() => {
            return request.get({
                url,
                qs: data,
                headers
            });
        });
    }
    logGet(url, data) {
        logger.info('api call [GET]', url + '?' + qs.stringify(data));
    }
    post(url, data, headers) {
        this.logPost(url, data);
        return this.parse(() => {
            return request.post({
                url,
                form: data,
                headers
            });
        });
    }
    logPost(url, data) {
        if (_.isString(data)) {
            logger.info('api call [POST]', url + '?' + data);
        } else {
            logger.info('api call [POST]', url + '?' + qs.stringify(data));
        }
    }
    upload() {
    }
    download() {
    }
    parse(req) {
        return new Promise((resolve, reject) => {
            let buffers = [], response;

            req()
            .on('error', error => {
                if (error) {
                    return reject(API_ERROR);
                }
            })
            .on('data', (chunk) => {
                buffers.push(chunk);
            })
            .on('response', (res) => {
                response = res;
            })
            .on('end', () => {
                console.log(response.length);
                if (buffers) {
                    // TODO 判断文件
                    try {
                        let jsonData = JSON.parse(buffers.toString('utf-8'));

                        return resolve(jsonData);
                    } catch (error) {
                        return reject(API_INTERNAL_ERROR);
                    }
                }
                return reject(API_INTERNAL_ERROR);
            });
        });
    }
}

module.exports = Api;