89 lines
2.5 KiB
JavaScript
89 lines
2.5 KiB
JavaScript
const path = require('path');
|
|
const chalk = require('chalk');
|
|
|
|
const { Util } = require('../../../util/');
|
|
|
|
const MongodbTable = require('./MongodbTable.js');
|
|
const MariadbTable = require('./MariadbTable.js');
|
|
|
|
const Constants = {
|
|
Tables: {
|
|
'mongodb': MongodbTable,
|
|
'mariadb': MariadbTable
|
|
}
|
|
};
|
|
|
|
class Provider {
|
|
|
|
constructor(client, opts) {
|
|
|
|
if(!opts.config) throw new Error('No config file provided!');
|
|
this.config = opts.config[opts.name];
|
|
if(this.config && (!this.config.database || !this.config.host)) throw new Error('Invalid config file provided!' + JSON.stringify(this.config));
|
|
|
|
this.client = client;
|
|
this.storageManager = client.storageManager;
|
|
|
|
this.name = opts.name;
|
|
this.connection = null;
|
|
this.db = null;
|
|
|
|
this.tables = {};
|
|
|
|
this._initialized = false;
|
|
this._class = Constants.Tables[opts.name];
|
|
|
|
}
|
|
|
|
async loadTables() {
|
|
|
|
const directory = path.join(process.cwd(), 'structure/storage/');
|
|
const files = await Util.readdirRecursive(path.join(directory, `tables/${this.name}`));
|
|
|
|
const loaded = [];
|
|
|
|
for(const file of files) {
|
|
const func = require(file);
|
|
if(typeof func !== 'function') {
|
|
this.storageManager._error("Attempted to index an invalid function as a table.", this);
|
|
delete require.cache[file];
|
|
continue;
|
|
}
|
|
const table = new func(this.client, this);
|
|
if(this._class && !(table instanceof this._class)) {
|
|
this.storageManager._error("Attempted to load an invalid class as a table.", this);
|
|
delete require.cache[file];
|
|
continue;
|
|
}
|
|
|
|
loaded.push(await this.loadTable(table));
|
|
|
|
}
|
|
|
|
for(const table of this.config.tables) {
|
|
if(this.tables[table]) continue;
|
|
else loaded.push(await this.loadTable(new this._class(this.client, this, {
|
|
name: table
|
|
})));
|
|
}
|
|
|
|
return loaded;
|
|
|
|
}
|
|
|
|
async loadTable(table) {
|
|
|
|
if(this.tables[table.name]) {
|
|
this.storageManager._error("Attempted to load an existing table.", table);
|
|
return null;
|
|
}
|
|
|
|
this.tables[table.name] = table;
|
|
this.storageManager._log(`Table ${chalk.bold(table.name)} was ${chalk.bold('loaded')}.`, table);
|
|
return table;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = Provider; |