-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtools.js
More file actions
102 lines (86 loc) · 2.71 KB
/
Copy pathtools.js
File metadata and controls
102 lines (86 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const VError = require('verror');
module.exports = function () {
const di = new require('./index.js')();
function registerModuleByPath(servicePath, serviceName) {
if (_.includes(servicePath, '.test.js' )) {
return null;
}
try {
let module = require(servicePath);
if (module.default) {
module = module.default
}
di.registerModule(module, serviceName);
} catch (e) {
if (_.includes(['MODULE_NOT_FOUND'], e.code)) {
throw new VError(e, `Module "${serviceName}" not found in ${servicePath}`);
} else {
throw new VError(e, `Can not initialize the module: ${serviceName} [${servicePath}]`);
}
}
}
function registerNodeModule(modulePath, implementations, name) {
let serviceName = modulePath;
if (name) {
serviceName = name;
}
registerModuleByPath(modulePath, serviceName)
_.forEach(implementations, (implementation)=>{
console.log(modulePath, serviceName, implementation);
registerModuleByPath(
`${modulePath}/implementations/${implementation}`,
`${serviceName}-${implementation}`
);
})
}
function registerDir(dir) {
const serviceDirectories = fs.readdirSync(dir).filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
_.forEach(serviceDirectories, function (serviceDirectory){
registerModuleDir(dir + '/' + serviceDirectory, serviceDirectory);
});
}
function registerModuleDir(dir, name) {
registerServiceDirectory(dir, 'index.js', {name});
}
function registerServiceDirectory(dir, defaultServiceName, options) {
let servicePath = dir;
let serviceName = defaultServiceName;
if (options.name) {
serviceName = options.name;
}
registerModuleByPath(servicePath, serviceName);
const impDir = [servicePath, 'implementations'].join('/')
try {
fs.accessSync(impDir);
registerImplementations(impDir, serviceName);
} catch (e) {
if (!_.includes(['ENOENT', 'ENOTDIR'], e.code)) {
throw e;
}
}
}
function registerImplementations(dir, prefix) {
const serviceDirectories = fs.readdirSync(dir);
_.forEach(serviceDirectories, function (serviceDirectory){
const servicePath = [dir, serviceDirectory].join('/');
const basename = path.basename(serviceDirectory, '.js');
serviceDirectory = `${prefix}-${basename}`;
registerModuleByPath(servicePath, serviceDirectory);
});
}
function getDI() {
return di;
}
return Object.freeze({
registerDir,
registerModuleDir,
registerNodeModule,
getDI: getDI
});
}