galactic-bot/storage/StorageManager.js

65 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-04-08 16:27:34 +02:00
const { Collection } = require('../util/');
2020-04-11 21:16:37 +02:00
const path = require('path');
const fs = require('fs');
2020-04-08 16:27:34 +02:00
class StorageManager {
2020-04-11 21:16:37 +02:00
constructor(manager, options = {}) {
2020-04-08 16:27:34 +02:00
2020-04-11 21:16:37 +02:00
this.manager = manager;
2020-04-14 08:41:42 +02:00
this.providers = new Collection();
2020-04-11 21:16:37 +02:00
this.options = options;
2020-04-08 16:27:34 +02:00
}
2020-04-09 16:30:52 +02:00
async initialize() {
2020-04-14 08:41:42 +02:00
this.manager.logger.write('debug', "Initializing storage providers.");
2020-04-11 21:16:37 +02:00
let _providers = path.join(process.cwd(), 'storage', 'providers');
let providers = fs.readdirSync(_providers);
for(let _provider of providers) {
let provider = require(path.join(_providers, _provider));
provider = new provider(this.manager, this.options);
await provider.init();
this.providers.set(provider.name, provider);
}
2020-04-09 16:30:52 +02:00
}
async _handleStorageRequest(shard, message) {
// vv TO BE GENERATED ON CLIENT vv
//`${shard.id}-${new Date().getTime().toString(36)
if(!message.provider) return this._send(shard, { error: true, message: "Provider not provided" });
if(!this.providers.has(message.provider)) return this._send(shard, { error: true, message: `Invalid provider, expected 'mongodb' or 'mariadb', got '${message.provider}'` });
if(!message.query) return this._send(shard, { error: true, message: `Missing query.` });
const response = await this.providers.get(message.provider)._query(message.query);
if(response.error) {
this.manager.logger.write('error', `Provider ${message.provider} errored: ${response.error.message}`, shard);
return this._send(shard, error);
}
}
_send(shard, message) {
shard.send({
_storage: true,
id: message.id,
error: message.error,
message: message.message
})
}
2020-04-08 16:27:34 +02:00
}
module.exports = StorageManager;