From f6fb3b213d9575b19c985be4b92364a273d3cbd6 Mon Sep 17 00:00:00 2001 From: Alrik Zachert Date: Sun, 8 Nov 2015 01:08:48 +0100 Subject: [PATCH] Add support for auto loading services when defined as string see issue #18 --- Application.js | 19 +++++++++++++++++-- test/Application.js | 23 +++++++++++++++++++++++ test/lib/Service.js | 14 ++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 test/lib/Service.js diff --git a/Application.js b/Application.js index 66e2d8c..157c0fa 100644 --- a/Application.js +++ b/Application.js @@ -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); @@ -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; diff --git a/test/Application.js b/test/Application.js index 13d24fd..12b1a68 100644 --- a/test/Application.js +++ b/test/Application.js @@ -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') + ); + }); }); diff --git a/test/lib/Service.js b/test/lib/Service.js new file mode 100644 index 0000000..619b204 --- /dev/null +++ b/test/lib/Service.js @@ -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;