-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
47 lines (43 loc) · 1.88 KB
/
app.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
const debug = require('debug')('saas-api-gateway:app')
const ora = require('ora')
class Ctl {
constructor() {
this.init()
}
async init() {
try {
require('./config')
this.components = {}
process.env.COMPONENTS.split(',').reduce((prev, componentFolderName) => {
return prev.then(async () => { await this.use(componentFolderName) })
}, Promise.resolve()).then(async () => {
// Do some stuff after all components being loaded
if(this.components['ServiceWatcher'] !== undefined && this.components['WebServer'] !== undefined) {
await this.components['ServiceWatcher'].discovery()
}
})
} catch (error) {
console.error(error)
process.exit(1)
}
}
async use(componentFolderName) {
let spinner = ora(`Registering component : ${componentFolderName}`).start()
try {
// Component dependency injections with inversion of control based on events emitted between components
// Component is an async singleton - requiring it returns a reference to an instance
const component = await require(`${__dirname}/components/${componentFolderName}`)(this)
debug(component.id)
this.components[component.id] = component // We register the instancied component reference in app.components object
spinner.succeed(`Registered component : ${component.id}`)
} catch (e) {
if (e.name == "COMPONENT_MISSING") {
return spinner.warn(`Skipping ${componentFolderName} - this component depends on : ${e.missingComponents}`)
}
spinner.fail(`Error in component loading : ${componentFolderName}`)
console.error(debug.namespace, e)
process.exit(1)
}
}
}
new Ctl()