galactic-bot/structure/client/TransactionHandler.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

const Collection = require('../../util/Collection.js');
2020-04-14 17:05:56 +02:00
class TransactionHandler {
constructor(client) {
this.client = client;
this.transactions = new Collection();
}
send(message, options = {}) {
2020-04-14 17:05:56 +02:00
2020-04-17 22:18:16 +02:00
/** Message structure
* {
* provider: string, -- mongodb or mariadb
* 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
* }
* }
*/
2020-04-14 17:05:56 +02:00
return new Promise((resolve, reject) => {
const id = this.transactionID;
this.transactions.set(id, { id, resolve, reject } );
2020-04-14 17:05:56 +02:00
process.send({ _storage: true, transactionID: id, ...message, ...options });
2020-04-14 17:05:56 +02:00
});
}
_receive(message) {
if(!message.transactionID) return undefined;
const transaction = this.transactions.get(message.transactionID);
if(!transaction) return undefined;
if(message.error) transaction.reject(message.message);
else transaction.resolve(message.result);
this.transactions.delete(message.transactionID);
}
2020-04-14 17:05:56 +02:00
get transactionID() {
return `${[ this.client.shard.ids ]}-${Date.now().toString(36)}`;
}
}
module.exports = TransactionHandler;