82 lines
2.6 KiB
JavaScript
82 lines
2.6 KiB
JavaScript
const path = require('path');
|
|
|
|
const { EventEmitter } = require('events');
|
|
const { Collection, Util } = require('../../util/');
|
|
|
|
const { Component, Module } = require('../../structure/interfaces');
|
|
|
|
class Registry extends EventEmitter {
|
|
|
|
constructor(client) {
|
|
|
|
super();
|
|
|
|
this.client = client;
|
|
this.components = new Collection();
|
|
|
|
}
|
|
|
|
async loadComponents(dir, classToHandle) {
|
|
|
|
const directory = path.join(process.cwd(), 'structure/client/', 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;
|
|
}
|
|
|
|
console.log(directory);
|
|
|
|
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 }));
|
|
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);
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = Registry; |