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)}` //NULL RESPONSE IF COLLECTION DOES NOT EXIST!! //EMPTY OBJECT IF NOTHING MATCHED!! /** Message structure * { * provider: string, -- mongodb or mariadb * transactionID: string, * request: { * type: string, -- The function to use from this class, ex. findOne * collection: string, -- Which collection to query from * query: { }, -- Actual search query * data: { } -- If the operation is to update or insert something, this is what to insert * } * } */ 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 && 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;