salix/front/core/lib/module-loader.js

96 lines
3.4 KiB
JavaScript
Raw Normal View History

2018-02-10 15:18:01 +00:00
import ngModule from '../module';
import moduleImport from 'module-import';
2018-08-30 09:02:50 +00:00
factory.$inject = ['$http', '$window', '$ocLazyLoad', '$translatePartialLoader', '$translate', '$q'];
export function factory($http, $window, $ocLazyLoad, $translatePartialLoader, $translate, $q) {
class ModuleLoader {
constructor() {
this._loaded = {};
}
load(moduleName, validations) {
let moduleConf = $window.routes.find(i => i && i.module == moduleName);
if (!moduleConf)
return $q.reject(new Error(`Module not found: ${moduleName}`));
let loaded = this._loaded;
if (loaded[moduleName] === true)
return Promise.resolve(true);
if (loaded[moduleName] instanceof Promise)
return loaded[moduleName];
if (loaded[moduleName] === false)
2018-08-31 11:06:39 +00:00
return $q.reject(new Error(`Module dependency loop detected: ${moduleName}`));
loaded[moduleName] = false;
let depPromises = [];
let deps = moduleConf.dependencies;
if (deps) {
for (let dep of deps)
depPromises.push(this.load(dep, validations));
}
loaded[moduleName] = new Promise((resolve, reject) => {
Promise.all(depPromises).then(() => {
let promises = [];
$translatePartialLoader.addPart(moduleName);
promises.push(new Promise(resolve => {
$translate.refresh().then(
() => resolve(),
() => resolve()
);
}));
if (validations) {
promises.push(new Promise(resolve => {
2019-01-25 16:05:53 +00:00
$http.get(`/${moduleName}/api/modelInfo`).then(
json => this.onValidationsReady(json, resolve),
() => resolve()
);
}));
}
promises.push(moduleImport(moduleName));
Promise.all(promises).then(() => {
loaded[moduleName] = true;
resolve($ocLazyLoad.load({name: moduleName}));
}).catch(reject);
}).catch(reject);
2017-09-21 06:48:25 +00:00
});
return loaded[moduleName];
2017-02-01 17:55:02 +00:00
}
onValidationsReady(json, resolve) {
let entities = json.data;
for (let entity in entities) {
2017-02-01 17:55:02 +00:00
let fields = entities[entity].validations;
for (let field in fields) {
2017-02-01 17:55:02 +00:00
let validations = fields[field];
for (let validation of validations)
2017-02-01 17:55:02 +00:00
this.parseValidation(validation);
}
}
Object.assign($window.validations, json.data);
resolve();
}
parseValidation(val) {
switch (val.validation) {
case 'custom':
// TODO: Replace eval
val.bindedFunction = eval(`(${val.bindedFunction})`);
break;
case 'format':
val.with = new RegExp(val.with);
break;
}
}
}
return new ModuleLoader();
2017-09-21 06:48:25 +00:00
}
2018-02-10 15:18:01 +00:00
ngModule.factory('vnModuleLoader', factory);