UNPKG

3.12 kBJavaScriptView Raw
1/**
2 * @license
3 * MOST Web Framework 2.0 Codename Blueshift
4 * Copyright (c) 2017, THEMOST LP All rights reserved
5 *
6 * Use of this source code is governed by an BSD-3-Clause license that can be
7 * found in the LICENSE file at https://themost.io/license
8 */
9///
10var ModuleLoaderStrategy = require('@themost/common/config').ModuleLoaderStrategy;
11var _ = require('lodash');
12
13/**
14 * @interface
15 * @property {string} serviceType
16 * @property {string} strategyType
17 */
18function ServiceConfigurationElement() {
19 //
20}
21
22/**
23 * @class
24 * @constructor
25 */
26function ServicesConfiguration() {
27 //
28}
29
30/**
31 * Adds application services as they are defined in application configuration services section
32 * @example
33 * # config/app.json
34 * {
35 * "services": [
36 * { "serviceType":"./services/my-service#MyService" },
37 * { "strategyType":"./services/my-service#MyStrategy", "serviceType":"./services/my-service#MyService" }
38 * ]
39 * }
40 *
41 * @param {HttpApplication} app
42 */
43ServicesConfiguration.config = function(app) {
44 /**
45 * @type {Array<ServiceConfigurationElement>}
46 */
47 var services = app.getConfiguration().getSourceAt('services');
48 if (_.isArray(services)) {
49 _.forEach(services,
50 /**
51 * @param {ServiceConfigurationElement} x
52 */
53 function(x) {
54 if (typeof x.serviceType === 'undefined' || x.serviceType === null) {
55 throw new Error('Invalid configuration. Service type cannot be empty at this context.');
56 }
57 var strategyType = x.strategyType || x.serviceType;
58 var StrategyCtor;
59 var ServiceCtor;
60 var typeModule;
61 var typeCtor;
62 var hashIndex = strategyType.indexOf('#');
63 if (hashIndex>-1) {
64 typeModule = app.getConfiguration().getStrategy(ModuleLoaderStrategy).require(strategyType.substr(0,hashIndex));
65 typeCtor = strategyType.substr(hashIndex+1,strategyType.length-hashIndex);
66 StrategyCtor = typeModule[typeCtor];
67 }
68 else {
69 StrategyCtor = app.getConfiguration().getStrategy(ModuleLoaderStrategy).require(strategyType);
70 }
71 hashIndex = x.serviceType.indexOf('#');
72 if (hashIndex>-1) {
73 typeModule = app.getConfiguration().getStrategy(ModuleLoaderStrategy).require(x.serviceType.substr(0,hashIndex));
74 typeCtor = x.serviceType.substr(hashIndex+1,x.serviceType.length-hashIndex);
75 ServiceCtor = typeModule[typeCtor];
76 }
77 else {
78 ServiceCtor = app.getConfiguration().getStrategy(ModuleLoaderStrategy).require(x.serviceType);
79 }
80 app.useStrategy(StrategyCtor, ServiceCtor);
81 });
82 }
83};
84
85
86if (typeof exports !== 'undefined')
87{
88 module.exports.ServiceConfigurationElement = ServiceConfigurationElement;
89 module.exports.ServicesConfiguration = ServicesConfiguration;
90}
\No newline at end of file