galactic-bot/Registry.js

73 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-04-08 16:27:34 +02:00
const { EventEmitter } = require('events');
2020-04-08 18:08:46 +02:00
const { Collection, Util } = require('./util/');
2020-04-08 16:27:34 +02:00
class Registry extends EventEmitter {
2020-04-08 18:08:46 +02:00
constructor(manager) {
this.components = new Collection();
}
async loadComponents() {
const directory = path.join(process.cwd(), 'structure/', dir); //Finds directory of component folder relative to current working directory.
const files = Util.readdirRecursive(directory); //Loops through all folders in the directory and returns the files.
const loaded = [];
for(const path of files) {
const func = require(path);
if(typeof func !== 'function') {
//this.client.logger.error("Attempted to index an invalid function as a component.");
continue;
}
const component = new func(this.client); //Instantiates the component class.
if(classToHandle && !(component instanceof classToHandle)) {
//this.client.logger.error("Attempted to load an invalid class.");
continue;
}
loaded.push(await this.loadComponent(component, path));
}
return loaded;
}
async loadComponent(component, directory) {
if(!(component instanceof Component)) {
//this.client.logger.error("Attempted to load an invalid component.");
return null;
}
if(this.components.has(component.resolveable)) {
//this.client.logger.error("Attempted to reload an existing component.");
return null;
}
if(directory) component.directory = directory;
if(component.module && typeof component.module === 'string') { //Sets modules or "groups" for each component, specified by their properties.
let module = this.components.get(`module:${component.module}`);
if(!module) module = await this.loadComponent(new Module(this.manager, { name: component.module }));
this.components.set(module.resolveable, module);
component.module = module;
module.components.set(component.resolveable, component);
}
this.components.set(component.resolveable, component);
this.emit('componentUpdate', { component, type: 'LOAD' });
return component;
}
async unloadComponent(component) {
this.components.delete(component.id);
}
2020-04-08 16:27:34 +02:00
}
module.exports = Registry;