import path, { dirname } from 'path'; import { fileURLToPath } from 'url'; /** * Main backend application */ class App{ constructor(){ this.root = path.resolve(dirname(fileURLToPath(import.meta.url)) + '/../../'); } /** * The plugins used by the application * @type {AppPlugin[]} */ plugins = []; /** * Declaration of plugin usage * @param {AppPlugin} plugin The plugin to be used */ async use(plugin){ this[plugin.name] = plugin; plugin.app = this; this.plugins.push(plugin); } /** * Initializes the application. All plugins are initialized at this stage */ async init(){ for (let p of this.plugins){ console.debug('Initializing', p.name) if(p.init) await p.init(this); } } /** * Imports modules as plugins in the app by a given list * @param {Array} modules Modules to be imported */ async importModules(modules){ const mods = {}; for (let m of modules){ mods[m.name] = (await import(`../${m.path}`))[m.name]; } for (let m of modules){ this.use(new mods[m.name]()) } } /** * Replaces a plugin * @param {AppPlugin} p Plugin to be replaced */ async replace(p){ let old = this[p.name]; this.plugins[this.plugins.indexOf(old)] = p; this[p.name] = p; p.app = this; if(p.init) await p.init(this); } /** * Starts the application. All Plugins are started at this point */ async start(){ for (let p of this.plugins){ console.debug('Starting', p.name) if(p.start) await p.start(this); } } } export default App;