Files
kami-parse-server/src/cloud-code/httpRequest.js

82 lines
2.5 KiB
JavaScript
Raw Normal View History

2016-03-08 00:15:17 -05:00
import request from 'request';
import HTTPResponse from './HTTPResponse';
import querystring from 'querystring';
2016-03-26 13:47:44 -04:00
import log from '../logger';
2016-03-08 00:15:17 -05:00
var encodeBody = function({body, headers = {}}) {
if (typeof body !== 'object') {
2016-03-08 00:15:17 -05:00
return {body, headers};
}
var contentTypeKeys = Object.keys(headers).filter((key) => {
return key.match(/content-type/i) != null;
});
if (contentTypeKeys.length == 0) {
// no content type
// As per https://parse.com/docs/cloudcode/guide#cloud-code-advanced-sending-a-post-request the default encoding is supposedly x-www-form-urlencoded
2016-03-26 13:47:44 -04:00
body = querystring.stringify(body);
headers['Content-Type'] = 'application/x-www-form-urlencoded';
2016-03-08 00:15:17 -05:00
} else {
/* istanbul ignore next */
if (contentTypeKeys.length > 1) {
2016-03-26 13:47:44 -04:00
log.error('Parse.Cloud.httpRequest', 'multiple content-type headers are set.');
2016-03-08 00:15:17 -05:00
}
// There maybe many, we'll just take the 1st one
var contentType = contentTypeKeys[0];
if (headers[contentType].match(/application\/json/i)) {
2016-03-08 00:15:17 -05:00
body = JSON.stringify(body);
} else if(headers[contentType].match(/application\/x-www-form-urlencoded/i)) {
body = querystring.stringify(body);
}
}
2016-03-08 00:15:17 -05:00
return {body, headers};
}
module.exports = function(options) {
var callbacks = {
success: options.success,
error: options.error
};
delete options.success;
delete options.error;
delete options.uri; // not supported
2016-03-08 00:15:17 -05:00
options = Object.assign(options, encodeBody(options));
// set follow redirects to false by default
options.followRedirect = options.followRedirects == true;
// support params options
if (typeof options.params === 'object') {
options.qs = options.params;
} else if (typeof options.params === 'string') {
options.qs = querystring.parse(options.params);
}
// force the response as a buffer
options.encoding = null;
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) {
if (callbacks.error) {
callbacks.error(error);
}
return reject(error);
2016-03-02 16:43:44 -05:00
}
const httpResponse = new HTTPResponse(response, body);
2016-03-26 13:47:44 -04:00
// Consider <200 && >= 400 as errors
if (httpResponse.status < 200 || httpResponse.status >= 400) {
if (callbacks.error) {
callbacks.error(httpResponse);
}
return reject(httpResponse);
} else {
if (callbacks.success) {
callbacks.success(httpResponse);
}
return resolve(httpResponse);
}
});
});
};
module.exports.encodeBody = encodeBody;