api.js 1.79 KB
const Context = require('./context');
const request = require('request');
const config = global.yoho.config;

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

class Api extends Context {
    constructor(domain = config.apiDomain.auth) {
        super();
        this.domain = domain;
    }
    get(url, data, headers) {
        return this.parse(() => {
            return request.get({
                url,
                qs: data,
                headers,
            });
        });
    }
    post(url, data, headers) {
        return this.parse(() => {
            return request.post({
                url,
                form: data,
                headers,
            });
        });
    }
    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;