const { Collection } = require('../util/'); const path = require('path'); const fs = require('fs'); class StorageManager { constructor(manager, options = {}) { this.manager = manager; this.providers = new Collection(); this.options = options; } async initialize() { this.manager.logger.write('debug', "Initializing storage providers."); 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); } return this; } async _handleStorageRequest(shard, message) { // vv TO BE GENERATED ON CLIENT vv // Transaction ID concept //`${shard.id}-${new Date().getTime().toString(36)}` if(!message.provider) return this._send(shard, { error: true, message: "Provider not provided", transactionID: message.transactionID }); if(!this.providers.has(message.provider)) return this._send(shard, { error: true, message: `Invalid provider, expected 'mongodb' or 'mariadb', got '${message.provider}'`, transactionID: message.transactionID }); if(!message.request) return this._send(shard, { error: true, message: `Missing request.`, transactionID: message.transactionID }); const response = await this.providers.get(message.provider)._query(message.request); if(response.error) { this.manager.logger.write('error', `Provider ${message.provider} errored: ${response.message}`, shard); return this._send(shard, response.error); } this._send(shard, { transactionID: message.transactionID, result: response }); } _send(shard, message) { shard.send({ _storage: true, transactionID: message.transactionID, id: message.id, error: message.error, message: message.message, result: message.result }); } } module.exports = StorageManager;