123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- "use strict";
- var _querystring = _interopRequireDefault(require("querystring"));
- var _logger = _interopRequireDefault(require("./logger"));
- var _followRedirects = require("follow-redirects");
- var _url = require("url");
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
- class HTTPResponse {
- constructor(response, body) {
- let _text, _data;
- this.status = response.statusCode;
- this.headers = response.headers || {};
- this.cookies = this.headers['set-cookie'];
- if (typeof body == 'string') {
- _text = body;
- } else if (Buffer.isBuffer(body)) {
- this.buffer = body;
- } else if (typeof body == 'object') {
- _data = body;
- }
- const getText = () => {
- if (!_text && this.buffer) {
- _text = this.buffer.toString('utf-8');
- } else if (!_text && _data) {
- _text = JSON.stringify(_data);
- }
- return _text;
- };
- const getData = () => {
- if (!_data) {
- try {
- _data = JSON.parse(getText());
- } catch (e) {
-
- }
- }
- return _data;
- };
- Object.defineProperty(this, 'body', {
- get: () => {
- return body;
- }
- });
- Object.defineProperty(this, 'text', {
- enumerable: true,
- get: getText
- });
- Object.defineProperty(this, 'data', {
- enumerable: true,
- get: getData
- });
- }
- }
- const clients = {
- 'http:': _followRedirects.http,
- 'https:': _followRedirects.https
- };
- function makeCallback(resolve, reject) {
- return function (response) {
- const chunks = [];
- response.on('data', chunk => {
- chunks.push(chunk);
- });
- response.on('end', () => {
- const body = Buffer.concat(chunks);
- const httpResponse = new HTTPResponse(response, body);
-
- if (httpResponse.status < 200 || httpResponse.status >= 400) {
- return reject(httpResponse);
- } else {
- return resolve(httpResponse);
- }
- });
- response.on('error', reject);
- };
- }
- const encodeBody = function ({
- body,
- headers = {}
- }) {
- if (typeof body !== 'object') {
- return {
- body,
- headers
- };
- }
- var contentTypeKeys = Object.keys(headers).filter(key => {
- return key.match(/content-type/i) != null;
- });
- if (contentTypeKeys.length == 0) {
-
-
- body = _querystring.default.stringify(body);
- headers['Content-Type'] = 'application/x-www-form-urlencoded';
- } else {
-
- if (contentTypeKeys.length > 1) {
- _logger.default.error('Parse.Cloud.httpRequest', 'multiple content-type headers are set.');
- }
-
- var contentType = contentTypeKeys[0];
- if (headers[contentType].match(/application\/json/i)) {
- body = JSON.stringify(body);
- } else if (headers[contentType].match(/application\/x-www-form-urlencoded/i)) {
- body = _querystring.default.stringify(body);
- }
- }
- return {
- body,
- headers
- };
- };
- function httpRequest(options) {
- let url;
- try {
- url = (0, _url.parse)(options.url);
- } catch (e) {
- return Promise.reject(e);
- }
- options = Object.assign(options, encodeBody(options));
-
- if (typeof options.params === 'object') {
- options.qs = options.params;
- } else if (typeof options.params === 'string') {
- options.qs = _querystring.default.parse(options.params);
- }
- const client = clients[url.protocol];
- if (!client) {
- return Promise.reject(`Unsupported protocol ${url.protocol}`);
- }
- const requestOptions = {
- method: options.method,
- port: Number(url.port),
- path: url.pathname,
- hostname: url.hostname,
- headers: options.headers,
- encoding: null,
- followRedirects: options.followRedirects === true
- };
- if (requestOptions.headers) {
- Object.keys(requestOptions.headers).forEach(key => {
- if (typeof requestOptions.headers[key] === 'undefined') {
- delete requestOptions.headers[key];
- }
- });
- }
- if (url.search) {
- options.qs = Object.assign({}, options.qs, _querystring.default.parse(url.query));
- }
- if (url.auth) {
- requestOptions.auth = url.auth;
- }
- if (options.qs) {
- requestOptions.path += `?${_querystring.default.stringify(options.qs)}`;
- }
- if (options.agent) {
- requestOptions.agent = options.agent;
- }
- return new Promise((resolve, reject) => {
- const req = client.request(requestOptions, makeCallback(resolve, reject, options));
- if (options.body) {
- req.write(options.body);
- }
- req.on('error', error => {
- reject(error);
- });
- req.end();
- });
- }
- module.exports = httpRequest;
- module.exports.encodeBody = encodeBody;
- module.exports.HTTPResponse = HTTPResponse;
|