-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
52 lines (47 loc) · 2.15 KB
/
app.js
File metadata and controls
52 lines (47 loc) · 2.15 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
const debug = require('debug')('saas-api-gateway:app')
const ora = require('ora')
class Ctl {
constructor() {
this.init()
}
async init() {
try {
require('./config')
const DatabaseService = require('./lib/sqlite')
await DatabaseService.init()
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()
}
if (this.components['ApiWatcher'] !== undefined && this.components['WebServer'] !== undefined) {
await this.components['ApiWatcher'].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)
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()