2020-09-08 08:11:42 +00:00
|
|
|
import Util from './core/util.mjs'
|
|
|
|
import { readFileSync } from 'fs'
|
2020-09-09 15:41:05 +00:00
|
|
|
import getLog from './core/log.mjs'
|
2020-09-08 08:11:42 +00:00
|
|
|
import lowdb from './core/db.mjs'
|
2020-09-09 15:41:05 +00:00
|
|
|
import Core from './core/core.mjs'
|
2020-09-08 08:11:42 +00:00
|
|
|
|
|
|
|
export default class ServiceCore {
|
|
|
|
constructor(name, root_import_meta_url) {
|
|
|
|
if (!root_import_meta_url) {
|
|
|
|
throw new Error('ServiceCore must be called with the full string from "import.meta.url" from a file residing in the root directory')
|
|
|
|
}
|
|
|
|
this._root_import_meta_url = root_import_meta_url
|
|
|
|
this.util = new Util(this._root_import_meta_url)
|
|
|
|
this.log = getLog(name)
|
|
|
|
this.db = null
|
|
|
|
this.config = null
|
|
|
|
this.core = null
|
|
|
|
}
|
|
|
|
|
|
|
|
close(err) {
|
|
|
|
if (err) {
|
2020-09-09 15:41:05 +00:00
|
|
|
this.log.fatal(err, 'App recorded a fatal error')
|
2020-09-08 08:11:42 +00:00
|
|
|
process.exit(4)
|
|
|
|
}
|
2020-09-09 15:41:05 +00:00
|
|
|
this.log.warn('App asked to be restarted')
|
2020-09-08 08:11:42 +00:00
|
|
|
process.exit(0)
|
|
|
|
}
|
|
|
|
|
2020-09-09 15:41:05 +00:00
|
|
|
async init(module = null) {
|
2020-09-08 08:11:42 +00:00
|
|
|
try {
|
|
|
|
this.config = JSON.parse(readFileSync(this.util.getPathFromRoot('./config.json')))
|
|
|
|
} catch (err) {
|
|
|
|
throw new Error('Unable to read config.json from root directory: ' + err)
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
this.db = await lowdb(this.util, this.log)
|
|
|
|
} catch (err) {
|
|
|
|
throw new Error('Unable to read initialise lowdb: ' + err)
|
|
|
|
}
|
|
|
|
|
|
|
|
this.core = new Core(this.util, this.config, this.db, this.log, (err) => this.close(err))
|
2020-09-09 15:41:05 +00:00
|
|
|
|
|
|
|
if (module) {
|
|
|
|
return this.startModule(module)
|
|
|
|
}
|
2020-09-08 08:11:42 +00:00
|
|
|
}
|
|
|
|
|
2020-09-09 15:41:05 +00:00
|
|
|
startModule(module) {
|
|
|
|
return this.core.startModule(module, this.config.devPort)
|
2020-09-08 08:11:42 +00:00
|
|
|
}
|
|
|
|
}
|