Skip to content

Commit

Permalink
Added HtttpComponent
Browse files Browse the repository at this point in the history
  • Loading branch information
Igor Drobiazko committed Sep 16, 2014
1 parent b605041 commit 9ee057c
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 39 deletions.
36 changes: 0 additions & 36 deletions lib/component.js

This file was deleted.

52 changes: 52 additions & 0 deletions lib/httpComponent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var request = require("request");
var Q = require("q");
var messages = require('./messages.js');

exports.HttpComponent = HttpComponent;

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

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

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");
}

var self = this;
var emitter = this.component;

Q.nfcall(request[method], requestOptions)
.then(transformArrayToObject)
.then(self.handleResponse)
.then(emitMessage)
.fail(handleError)
.done(done);

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

function emitMessage(msg) {
emitter.emit('data', msg);
}

function handleError(err) {
console.log(err);
emitter.emit('error', err);
}

function done() {
emitter.emit('end');
}
};
9 changes: 6 additions & 3 deletions spec/component.spec.js → spec/httpComponent.spec.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
describe('component.js', function () {
describe('Http Component', function () {

var Q = require('q');
var nock = require('nock');
var component = require('../lib/component.js');
var HttpComponent = require('../lib/httpComponent.js').HttpComponent;
var messages = require('../lib/messages.js');

it('should work', function () {
Expand All @@ -26,9 +26,12 @@ describe('component.js', function () {
return Q(messages.newMessageWithBody(response.body));
}

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

runAndExpect(
function () {
component.simpleHttpRequestComponent.bind(emitter)('get', options, handleResponse);
component.exec('get', options);
},
function () {
return emitter.emit.callCount === 2;
Expand Down

0 comments on commit 9ee057c

Please sign in to comment.