galactic-bot/structure/client/TransactionHandler.js

49 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-04-14 17:05:56 +02:00
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 undefined;
2020-04-14 17:05:56 +02:00
const transaction = this.transactions.get(message.transactionID);
if(!transaction) return undefined;
2020-04-14 17:05:56 +02:00
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
}
_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;