Skip to content

Commit

Permalink
Start using promises internally for service methods
Browse files Browse the repository at this point in the history
  • Loading branch information
SomeoneWeird committed Jan 23, 2016
1 parent ce4904d commit 24fd6ad
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 11 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"homepage": "https://github.com/hudson-taylor/hudson-taylor",
"dependencies": {
"async": "~1.4.0",
"bluebird": "^3.1.1",
"body-parser": "~1.14.1",
"express": "~4.13.2",
"ht-schema": "~3.1.4"
Expand Down
31 changes: 22 additions & 9 deletions src/service.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

"use strict";

const async = require("async");
const s = require("ht-schema");
const async = require("async");
const s = require("ht-schema");
const bluebird = require("bluebird");

const utils = require("./utils");

Expand Down Expand Up @@ -59,11 +60,7 @@ let Service = function Service(Transports, config) {
let _tmp = this._methods[context.method];
if(!_tmp) return cb({ error: "unknown-method", method: context.method });

let finish = (err, response) => {

if(err) {
return cb(err);
}
let finish = (response) => {

let _afterMiddleware = this._middleware.after.filter((m) => {
if(m.method && m.method !== context.method) return false;
Expand Down Expand Up @@ -95,12 +92,28 @@ let Service = function Service(Transports, config) {
error: err.message
});
}
return _tmp.fn(data, finish);
return go();
});
} else {
_tmp.fn(data, finish);
go();
}

function go() {

// Handle both callbacks and promises here.
let callbackHandler = function(err, response) {
if(err) return cb(err);
return finish(response);
}

let response = _tmp.fn(data, callbackHandler);

if(response && typeof response.then === 'function') {
callbackHandler = null;
return response.then(finish).catch(cb);
}

}

});

Expand Down
23 changes: 21 additions & 2 deletions test-src/service.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

"use strict";

const assert = require('assert');
const s = require('ht-schema');
const assert = require('assert');
const s = require('ht-schema');
const bluebird = require('bluebird');

const Service = require('../lib/service');

Expand Down Expand Up @@ -123,6 +124,24 @@ describe("Service", function() {

});

it("should allow returning promise from function", function(done) {

let service = new Service();

service.on("test", function() {
return new bluebird.Promise(function(resolve, reject) {
return resolve(_data);
});
});

service.call("test", null, function(err, response) {
assert.ifError(err);
assert.deepEqual(response, _data);
done();
});

});

});

describe("listen", function() {
Expand Down

0 comments on commit 24fd6ad

Please sign in to comment.