import * as request from 'request';
import { BizError } from './bizError';

export function get(url:string, query?, headers?, timeOut?) {
    timeOut = timeOut || 5000;
    if (!url || (url.search(/http:/) && url.search(/https:/)) ) throw new BizError(!url ? "请求地址为空" : "请求地址错误");
    return new Promise((resolve, reject)=>{
        let paramater:any = { url, json:true, timeout:timeOut };
        if (query) paramater.qs = query;
        if (headers) paramater.headers = headers;
        request.get(paramater, function (err, res, body) {
           const success = !err && res && res == 200;
           let message = err || res.statusCode || "";
           resolve({success, message, body});
        })
    })
}


export function post(url, body, headers) {
    if (!url || (url.search(/http:/) && url.search(/https:/)) ) throw new BizError(!url ? "请求地址为空" : "请求地址错误");
    let header = {"content-type": "application/json"};  
    return new Promise((resolve, reject)=>{
        request({
            url: url,
            method: "POST",
            json: true,
            headers: Object.assign(header, headers),
            body: body
        }, function(err, res, body) {
            const success = !err && res && res == 200;
            let message = err || res.statusCode || "";
            resolve({success, message, body});
        });
    })
}

export function postForm(url, body) {
    if (!url || (url.search(/http:/) && url.search(/https:/)) ) throw new BizError(!url ? "请求地址为空" : "请求地址错误");
    return new Promise((resolve, reject)=>{
        request({
            url: url,
            method: "POST",
            json: true,
            form:body
        }, function(err, res, body) {
            const success = !err && res && res == 200;
            let message = err || res.statusCode || "";
            resolve({success, message, body});
        });
    })
}
