galactic-bot/structure/client/Registry.js

83 lines
2.8 KiB
JavaScript
Raw Normal View History

2020-04-09 16:30:52 +02:00
const path = require('path');
const { Collection, Util } = require('../../util/');
const { Component, Module } = require('../../structure/interfaces');
2020-04-08 16:27:34 +02:00
2020-04-13 22:38:10 +02:00
class Registry {
2020-04-08 16:27:34 +02:00
constructor(client) {
2020-04-08 18:08:46 +02:00
this.client = client;
2020-04-08 18:08:46 +02:00
this.components = new Collection();
}
async loadComponents(dir, classToHandle) {
2020-04-08 18:08:46 +02:00
const directory = path.join(process.cwd(), 'structure/client/', dir); //Finds directory of component folder relative to current working directory.
2020-04-08 18:08:46 +02:00
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') {
2020-04-14 08:41:42 +02:00
this.client.logger.warn("Attempted to index an invalid function as a component.");
delete require.cache[path];
2020-04-08 18:08:46 +02:00
continue;
}
const component = new func(this.client); //Instantiates the component class.
if(classToHandle && !(component instanceof classToHandle)) {
2020-04-14 08:41:42 +02:00
this.client.logger.warn("Attempted to load an invalid class.");
delete require.cache[path];
2020-04-08 18:08:46 +02:00
continue;
}
loaded.push(await this.loadComponent(component, path));
}
return loaded;
}
async loadComponent(component, directory, silent = false) {
2020-04-08 18:08:46 +02:00
if(!(component instanceof Component)) {
delete require.cache[directory];
2020-04-14 08:41:42 +02:00
this.client.logger.warn("Attempted to load an invalid component.");
2020-04-08 18:08:46 +02:00
return null;
}
if(this.components.has(component.resolveable)) {
2020-04-14 08:41:42 +02:00
this.client.logger.warn("Attempted to reload an existing component.");
2020-04-08 18:08:46 +02:00
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.client, { name: component.module }));
2020-04-08 18:08:46 +02:00
this.components.set(module.resolveable, module);
component.module = module;
module.components.set(component.resolveable, component);
}
this.components.set(component.resolveable, component);
if(!silent) this.client.emit('componentUpdate', { component, type: 'LOAD' });
2020-04-08 18:08:46 +02:00
return component;
}
async unloadComponent(component) {
if(component.module) {
component.module.components.delete(component.resolveable);
}
this.components.delete(component.resolveable);
2020-04-08 18:08:46 +02:00
}
2020-04-08 16:27:34 +02:00
}
module.exports = Registry;