<commit_before>/**
 * Created by chkui on 2017/6/16.
 */

import context from '../../../config/server/context'
import {asyncLoader, isServerEvn} from '../util'

if (typeof require.ensure !== 'function') { //server without webpack
    require.ensure = function (dependencies, callback) {
        callback(require)
    }
}

let loader;
isServerEvn() && (loader = new asyncLoader({
    loader: (call)=> {
        require.ensure([], require => {
            call(require('http'))
        }, 'http')
    }
}))

//TODO 目前直接从全局环境获取配置
const __host = global ? global.serverHost : '127.0.0.1', //主机地址
    __port = 8080; //主机端口

/**
 *  通用网络请求工具
 *  @constructor {
 *      @param {string} method: 服务器调用方法["GET"|"POST"],
 *      @param {url} url: 访问路径
 *      @param {object|string} data: 要传递的数据
 *      @param {object} header: 要提交的头部 例如 {"Accept":"application/json"}
 *      @param {object} query: 服务器调用的query admin?a=a&b=b等价于{a:'a',b:'b'}
 *  }
 */
class serverNetwork {
    constructor(params) {
        const _this = this;
        this.callback = {};//所有回调方法
        this.params = params;
        this.onLoad = this.onLoad.bind(this);
        this.response = this.response.bind(this);
    }

    onLoad(http) {
        const params = this.params;
        this.request = http.request({
            method: params.method,
            host: context.host,
            port: context.port,
            path: params.url,
            headers: params.header
        }, this.response)
        this.request.on('error', (e) => {
            _this.callback.err(e, e.message)
            console.error(`请求遇到问题: ${e.message}`);
        });
        params.data && this.request.write(params.data);
        this.request.end();
    }

    /**
     * 发送方法
     * @returns {serverNetwork}
     */
    send() {
        loader.register(this.onLoad)
        return this;
    }

    response(res) {
        const _this = this;
        res.setEncoding('utf8');
        let body = "";
        res.on('data', (chunk)=> {
            body += chunk;
        });
        res.on('end', ()=> {
            body.startsWith("{") && (body = JSON.parse(body))
            _this.callback.suc(body);
        });
    }

    /**
     * 服务器正常响应回传的信息
     * @param fun(data)
     * @returns {serverNetwork}
     */
    suc(fun) {
        this.callback.suc = fun;
        return this;
    }

    /**
     * 服务器头部信息
     * @param fun(header)
     * @returns {serverNetwork}
     */
    headers(fun) {
        this.callback.headers = fun;
        return this;
    }

    /**
     * 服务器产生错误的回调
     * @param fun(err,res) err为错误信息,res为服务器回调信息
     */
    err(fun) {
        this.callback.err = fun;
        return this;
    }
}

export default serverNetwork<commit_msg>modify server network<commit_after>/**
 * Created by chkui on 2017/6/16.
 */

import {asyncLoader, isServerEvn} from '../../util'

if (typeof require.ensure !== 'function') { //server without webpack
    require.ensure = function (dependencies, callback) {
        callback(require)
    }
}

let loader;
isServerEvn() && (loader = new asyncLoader({
    loader: (call)=> {
        require.ensure([], require => {
            call(require('http'))
        }, 'http')
    }
}))

//TODO 目前直接从全局环境获取配置
const __host = global ? global.serverHost : '127.0.0.1', //主机地址
    __port = 8080; //主机端口

/**
 *  通用网络请求工具
 *  @constructor {
 *      @param {string} method: 服务器调用方法["GET"|"POST"],
 *      @param {url} url: 访问路径
 *      @param {object|string} data: 要传递的数据
 *      @param {object} header: 要提交的头部 例如 {"Accept":"application/json"}
 *      @param {object} query: 服务器调用的query admin?a=a&b=b等价于{a:'a',b:'b'}
 *  }
 */
class serverNetwork {
    constructor(params) {
        const _this = this;
        this.callback = {};//所有回调方法
        this.params = params;
        this.onLoad = this.onLoad.bind(this);
        this.response = this.response.bind(this);
    }

    onLoad(http) {
        const params = this.params;
        this.request = http.request({
            method: params.method,
            host: context.host,
            port: context.port,
            path: params.url,
            headers: params.header
        }, this.response)
        this.request.on('error', (e) => {
            _this.callback.err(e, e.message)
            console.error(`请求遇到问题: ${e.message}`);
        });
        params.data && this.request.write(params.data);
        this.request.end();
    }

    /**
     * 发送方法
     * @returns {serverNetwork}
     */
    send() {
        loader.register(this.onLoad)
        return this;
    }

    response(res) {
        const _this = this;
        res.setEncoding('utf8');
        let body = "";
        res.on('data', (chunk)=> {
            body += chunk;
        });
        res.on('end', ()=> {
            body.startsWith("{") && (body = JSON.parse(body))
            _this.callback.suc(body);
        });
    }

    /**
     * 服务器正常响应回传的信息
     * @param fun(data)
     * @returns {serverNetwork}
     */
    suc(fun) {
        this.callback.suc = fun;
        return this;
    }

    /**
     * 服务器头部信息
     * @param fun(header)
     * @returns {serverNetwork}
     */
    headers(fun) {
        this.callback.headers = fun;
        return this;
    }

    /**
     * 服务器产生错误的回调
     * @param fun(err,res) err为错误信息,res为服务器回调信息
     */
    err(fun) {
        this.callback.err = fun;
        return this;
    }
}

export default serverNetwork
{'fraction_non_alphanumeric': 0.1589895988112927, 'fraction_numerical': 0.006686478454680535, 'mean_word_length': 1.8843063738618104, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2325875', 'n_tokens_mistral': 1906, 'n_tokens_neox': 1937, 'n_words': 337}