Adds HTTPResponse object and lazy loading text and JSON

This commit is contained in:
Florent Vilmart
2016-03-07 23:53:23 -05:00
parent f40efe3923
commit 982fc72327
2 changed files with 24 additions and 9 deletions

View File

@@ -0,0 +1,21 @@
export default class HTTPResponse {
constructor(response) {
this.status = response.statusCode;
this.headers = response.headers;
this.buffer = response.body;
this.cookies = response.headers["set-cookie"];
}
get text() {
return this.buffer.toString('utf-8');
}
get data() {
if (!this._data) {
try {
this._data = JSON.parse(this.text);
} catch (e) {}
}
return this._data;
}
}

View File

@@ -1,6 +1,7 @@
var request = require("request"),
querystring = require('querystring'),
Parse = require('parse/node').Parse;
HTTPResponse = require('./HTTPResponse').HTTPResponse;
var encodeBody = function(options = {}) {
let body = options.body;
@@ -62,15 +63,8 @@ module.exports = function(options) {
}
return promise.reject(error);
}
var httpResponse = {};
httpResponse.status = response.statusCode;
httpResponse.headers = response.headers;
httpResponse.buffer = response.body;
httpResponse.cookies = response.headers["set-cookie"];
httpResponse.text = response.body.toString('utf-8');
try {
httpResponse.data = JSON.parse(httpResponse.text);
} catch (e) {}
let httpResponse = new HTTPResponse(response);
// Consider <200 && >= 400 as errors
if (httpResponse.status < 200 || httpResponse.status >= 400) {
if (callbacks.error) {