Skip to content

Commit

Permalink
Add support for auto loading services when defined as string
Browse files Browse the repository at this point in the history
see issue #18
  • Loading branch information
alrik committed Nov 8, 2015
1 parent 4a6fd8a commit f6fb3b2
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
19 changes: 17 additions & 2 deletions Application.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,17 @@ class Application extends Service {
let
serviceDefinition = servicesConfig[serviceKey];

if (typeof serviceDefinition === 'function') {
if (typeof serviceDefinition === 'function' || typeof serviceDefinition === 'string') {
serviceDefinition = {
service: serviceDefinition
};
}

if (serviceDefinition !== null && typeof serviceDefinition.service === 'function') {
if (serviceDefinition !== null && serviceDefinition.service) {
if (typeof serviceDefinition.service === 'string') {
serviceDefinition.service = this._loadService(serviceDefinition.service);
}

// instantiate the fetched service class.
let service = new (serviceDefinition.service)(serviceManager);
serviceManager.set(serviceKey, service);
Expand Down Expand Up @@ -192,6 +196,17 @@ class Application extends Service {

return this;
}

/**
* Load and return a service by its path.
*
* @param servicePath
* @returns {*}
* @private
*/
_loadService(servicePath) {
return require(servicePath);
}
}

module.exports = Application;
23 changes: 23 additions & 0 deletions test/Application.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,4 +309,27 @@ describe('kermit::application', function() {
'Expect service `test2` to be configured with no config through the service definition configKey property that equals `null`.'
);
});

it('should load services if defined as string.', function() {
var app = new Application;

app.configure({
configs: [{
app: {
services: {
test: __dirname + '/lib/Service',
test2: __dirname + '/../Service'
}
}
}]
}).bootstrap().launch();

assert(
app.getServiceManager().has('test')
);

assert(
app.getServiceManager().has('test2')
);
});
});
14 changes: 14 additions & 0 deletions test/lib/Service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* kermit - soa infrastructure for node js
*
* @copyright Copyright (c) 2015, Alrik Zachert
* @license https://gitlab.com/kermit-js/kermit/blob/master/LICENSE BSD-2-Clause
*/

"use strict";

const BaseService = require('../../Service');

class Service extends BaseService {}

module.exports = Service;

0 comments on commit f6fb3b2

Please sign in to comment.