galactic-bot/structure/interfaces/Component.js

79 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-04-08 18:08:46 +02:00
class Component {
constructor(client, opts = {}) {
2020-04-08 18:08:46 +02:00
if(!opts) return null;
this.client = client;
2020-04-08 18:08:46 +02:00
this.id = opts.id;
this.type = opts.type;
this.directory = null;
this.guarded = Boolean(opts.guarded);
this.disabled = Boolean(opts.disabled);
this.registry = this.client.registry;
2020-04-08 18:08:46 +02:00
}
enable() {
if(this.guarded) return { error: true, code: 'GUARDED' };
this.disabled = false;
2020-04-13 22:38:10 +02:00
this.client.emit('componentUpdate', { component: this, type: 'ENABLE' });
2020-04-08 18:08:46 +02:00
return { error: false };
}
disable() {
if(this.guarded) return { error: true, code: 'GUARDED' };
this.disabled = true;
2020-04-13 22:38:10 +02:00
this.client.emit('componentUpdate', { component: this, type: 'DISABLE' });
2020-04-08 18:08:46 +02:00
return { error: false };
}
unload() {
if(this.guarded) return { error: true, code: 'GUARDED' };
if(!this.directory) return { error: true, code: 'MISSING_DIRECTORY' };
this.registry.unloadComponent(this);
delete require.cache[this.filePath];
2020-04-13 22:38:10 +02:00
this.client.emit('componentUpdate', { component: this, type: 'UNLOAD' });
2020-04-08 18:08:46 +02:00
return { error: false };
}
reload(bypass = false) {
if(this.type === 'module') return { error: false };
if(this.guarded && !bypass) return { error: true, code: 'GUARDED' };
if(!this.directory || !require.cache[this.directory]) return { error: true, code: 'MISSING_DIRECTORY' };
let cached, newModule;
try {
cached = require.cache[this.directory];
delete require.cache[this.directory];
newModule = require(this.directory);
if(typeof newModule === 'function') {
newModule = new newModule(this.client);
2020-04-08 18:08:46 +02:00
}
this.registry.unloadComponent(this);
2020-04-13 22:38:10 +02:00
this.client.emit('componentUpdate', { component: this, type: 'UNLOAD' });
2020-04-08 18:08:46 +02:00
this.registry.loadComponent(newModule, this.directory);
} catch(error) {
if(cached) require.cache[this.directory] = cached;
return { error: true, code: 'MISSING_MODULE' };
}
return { error: false };
}
get resolveable() {
return `${this.type}:${this.id}`;
}
}
module.exports = Component;