@coolgk/utils
Version:
javascript, typescript utility and wrapper functions and classes: array, string, base64, ampq, bcrypt, cache, captcha, csv, email, jwt, number, pdf, tmp, token, unit conversion, url params, session, form data, google sign in, facebook sign in
59 lines (57 loc) • 1.93 kB
JavaScript
/*!
* @package @coolgk/utils
* @version 3.1.4
* @link https://github.com/coolgk/node-utils
* @license MIT
* @author Daniel Gong <daniel.k.gong@gmail.com>
*
* Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved.
* Licensed under the MIT License.
*/
;
Object.defineProperty(exports, "__esModule", { value: true });
const querystring_1 = require("querystring");
const url = require("url");
function send(urlString, options = {}) {
return new Promise((resolve, reject) => {
options = Object.assign(url.parse(urlString), options);
const request = require(options.protocol === 'http:' ? 'http' : 'https').request(options, (response) => {
response.setEncoding('utf8');
let data = '';
response.on('data', (chunk) => data += chunk);
response.on('end', () => {
const requestResponse = {
statusCode: response.statusCode,
headers: response.headers,
data,
get json() {
return JSON.parse(data);
}
};
resolve(requestResponse);
});
});
request.on('error', (error) => {
reject(error);
});
if (options.data) {
request.write(JSON.stringify(options.data));
}
request.end();
});
}
exports.send = send;
function get(urlString, options = {}) {
delete options.data;
return send(urlString, options);
}
exports.get = get;
function post(urlString, options = {}) {
options.headers = Object.assign(options.headers || {}, {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(querystring_1.stringify(options.data || {}))
});
options.method = 'POST';
return send(urlString, options);
}
exports.post = post;