-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (90 loc) · 2.98 KB
/
index.js
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
const async = require('async')
let osseus
const traceAndClarifyIfPossible = (config) => {
if (config && config.use_trace && config.env && config.env.toLowerCase() !== 'production') {
console.log('using trace-and-clarify-if-possible, MEMORY LEAKS EXPECTED!!')
require('trace-and-clarify-if-possible')
} else {
console.log('Not using trace-and-clarify-if-possible')
}
}
const requireModule = (moduleName) => {
try {
return require(moduleName)
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err
}
return module.parent.require(moduleName)
}
}
const init = async (config) => {
const log = msg => { if (config.debug) { console.log(msg) } }
return new Promise(async (resolve, reject) => {
config = config || await require('@colucom/osseus-config').init().catch(err => { reject(err) })
traceAndClarifyIfPossible(config)
osseus = {config: config}
const modules = {}
log(`osseus.config.keys: ${osseus.config.keys}`)
osseus.config.keys.forEach(async key => {
log(`key: ${key}`)
if (key.startsWith('osseus')) {
let loadModule = typeof osseus.config[key].load !== 'undefined' ? osseus.config[key].load : true
let isPrivate = typeof osseus.config[key].private !== 'undefined' ? osseus.config[key].private : false
let scope = osseus.config[key].scope
log(`${key} loadModule: ${loadModule}, isPrivate: ${isPrivate}, scope: ${scope}`)
if (loadModule) {
let moduleName = key.substring(7) // 'osseus_' length
let dependencies = osseus.config[key].dependencies || []
if (typeof dependencies === 'string') {
dependencies = dependencies.split(',')
}
log(`${key} dependencies: ${dependencies}`)
modules[moduleName] = dependencies
modules[moduleName].push(async () => {
key = key.replace('_', '-')
key = isPrivate ? key : (scope ? `@${scope}/${key}` : `@colucom/${key}`)
log(`require(${key}).init()...`)
try {
const _module = await requireModule(key).init(osseus)
log(`required: ${key}`)
if (_module.start) {
log(`${key}.start()...`)
await _module.start()
log(`started ${key}`)
}
osseus[moduleName] = _module
return _module
} catch (err) {
console.error(`osseus init`, err.stack)
reject(err)
}
})
} else {
console.warn(`not loading ${key}...`)
}
}
})
try {
async.auto(modules, err => {
if (err) return reject(err)
resolve(osseus)
})
} catch (err) {
reject(err)
}
})
}
const get = () => {
return new Promise(async (resolve, reject) => {
if (!osseus) {
osseus = await init().catch(err => { reject(err) })
resolve(osseus)
}
resolve(osseus)
})
}
module.exports = {
init: init,
get: get
}