Skip to content

Commit

Permalink
Added rebounds
Browse files Browse the repository at this point in the history
  • Loading branch information
Igor Drobiazko committed Sep 16, 2014
1 parent 9ee057c commit 50317d4
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
33 changes: 29 additions & 4 deletions lib/httpComponent.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
var request = require("request");
var Q = require("q");
var _ = require("underscore");
var messages = require('./messages.js');

exports.HttpComponent = HttpComponent;

function HttpComponent(component) {
this.component = component;
this.statusCodesToRebound = [];
this.responseHandler = null;
}

HttpComponent.prototype.onResponse = function onResponse(responseHandler) {
HttpComponent.prototype.success = function success(responseHandler) {
this.responseHandler = responseHandler;

return this;
};

HttpComponent.prototype.reboundOnStatusCode = function reboundOnStatusCode(statusCodes) {

var newCodes = typeof statusCodes === 'number' ? [statusCodes] : statusCodes;

if (!Array.isArray(newCodes)) {
throw new Error(statusCodes + ' must be either a number or an array of numbers');
}

var codes = this.statusCodesToRebound.concat(newCodes);

this.statusCodesToRebound = _.uniq(codes);

return this;
};

HttpComponent.prototype.exec = function exec(method, requestOptions) {
if (!this.responseHandler) {
throw new Error("Response handler is required. Please set it through HttpComponent.onResponse");
Expand All @@ -32,8 +49,8 @@ HttpComponent.prototype.exec = function exec(method, requestOptions) {

function transformArrayToObject(output) {
return Q({
response : output[0],
body : output[1]
response: output[0],
body: output[1]
});
}

Expand All @@ -43,7 +60,15 @@ HttpComponent.prototype.exec = function exec(method, requestOptions) {

function handleError(err) {
console.log(err);
emitter.emit('error', err);
var statusCode = err.statusCode;

if (~self.statusCodesToRebound.indexOf(statusCode)) {
emitter.emit('error', err);
} else {
emitter.emit('rebound', 'API responded with HTTP status code: '+statusCode);
}

emitter.emit('end');
}

function done() {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"dependencies": {
"request": "2.9.x",
"node-uuid": "1.3.3",
"q": "1.0.0"
"q": "1.0.0",
"underscore":"1.5.1"
},
"devDependencies": {
"nock": "0.27.2",
Expand Down
2 changes: 1 addition & 1 deletion spec/httpComponent.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('Http Component', function () {
}

var component = new HttpComponent(emitter)
.onResponse(handleResponse);
.success(handleResponse);

runAndExpect(
function () {
Expand Down

0 comments on commit 50317d4

Please sign in to comment.