galactic-bot/structure/client/TransactionHandler.js
2020-04-14 18:05:56 +03:00

45 lines
1.0 KiB
JavaScript

const { Collection } = require("discord.js");
class TransactionHandler {
constructor(client) {
this.client = client;
this.transactions = new Collection();
process.on('message', (message) => {
if(message._storage) this._receive(message);
});
}
_receive(message) {
if(!message.transactionID) return;
const transaction = this.transactions.get(message.transactionID);
if(message.error) transaction.reject(message.message);
else transaction.resolve(message.result);
}
_send(message, options = {}) {
return new Promise((resolve, reject) => {
const ID = this.transactionID;
this.transactions.set(ID, { id: ID, resolve, reject } );
process.send({ _storage: true, transactionID: ID, ...message, ...options });
});
}
get transactionID() {
return `${[ this.client.shard.ids ]}-${Date.now().toString(36)}`;
}
}
module.exports = TransactionHandler;