👔 Changed to transactions #297

This commit is contained in:
Axel Olausson Holtenäs 2022-05-29 19:56:35 +02:00
parent 880ad789c9
commit 75c9fdf438
No known key found for this signature in database
GPG key ID: 7BF6826B76382CBA
4 changed files with 101 additions and 110 deletions

View file

@ -1,43 +0,0 @@
import sleep from "../../helpers/sleep";
import logger from "../../logger";
import Chance from "chance";
export default async function saveUser(data: any, data2: any) {
process.nextTick(
async () => {
// Chance module
const chance = new Chance();
await sleep(
chance.integer({
min: 0,
max: 1,
}) *
10 +
1 * 100
); // 100 - 1000 random Number generator
data.save((_: any) =>
_
? logger?.error(
`ERROR Occurred while saving data (saveUser) \n${"=".repeat(
50
)}\n${`${_}\n${"=".repeat(50)}`}`
)
: logger?.silly(`Saved user: ${data.id} (saveUser)`)
);
if (data2) {
data2.save((_: any) =>
_
? logger?.error(
`ERROR Occurred while saving data (saveUser) \n${"=".repeat(
50
)}\n${`${_}\n${"=".repeat(50)}`}`
)
: logger?.silly(`Saved user: ${data2.id} (saveUser)`)
);
}
},
data,
data2
);
}

View file

@ -1,8 +0,0 @@
import logger from "../../logger";
export default function sleep(milliseconds: number) {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
logger?.silly(`Sleeping for ${milliseconds} milliseconds`);
});
}

View file

@ -7,8 +7,7 @@ import getEmbedConfig from "../../../../helpers/getEmbedConfig";
// Handlers // Handlers
import logger from "../../../../logger"; import logger from "../../../../logger";
// Helpers import mongoose from "mongoose";
import saveUser from "../../../../helpers/saveUser";
// Models // Models
import fetchUser from "../../../../helpers/fetchUser"; import fetchUser from "../../../../helpers/fetchUser";
@ -184,41 +183,58 @@ export default {
}); });
} }
const session = await mongoose.startSession();
session.startTransaction();
try {
// Withdraw amount from fromUserDB // Withdraw amount from fromUserDB
fromUserDB.credits -= optionAmount; fromUserDB.credits -= optionAmount;
// Deposit amount to toUserDB // Deposit amount to toUserDB
toUserDB.credits += optionAmount; toUserDB.credits += optionAmount;
// Save users await fromUserDB.save();
await saveUser(fromUserDB, toUserDB).then(async () => {
// Get DM user object
const dmUser = client.users.cache.get(optionUser.id);
if (dmUser == null) return; await toUserDB.save();
// Send DM to user await session.commitTransaction();
await dmUser } catch (error) {
.send({ await session.abortTransaction();
session.endSession();
logger.error(`${error}`);
return interaction.editReply({
embeds: [ embeds: [
embed embed
.setDescription( .setDescription(
`${ "An error occurred while trying to gift credits. Please try again."
user.tag )
} has gifted you ${optionAmount} credits with reason: ${ .setColor(errorColor),
],
});
} finally {
// ending the session
session.endSession();
}
// Get DM user object
const dmUser = client.users.cache.get(optionUser.id);
if (!dmUser) throw new Error("User not found");
// Send DM to user
await dmUser.send({
embeds: [
embed
.setDescription(
`${user.tag} has gifted you ${optionAmount} credits with reason: ${
optionReason || "unspecified" optionReason || "unspecified"
}` }`
) )
.setColor(successColor), .setColor(successColor),
], ],
}) });
.catch(async (error) =>
logger.error(`[Gift] Error sending DM to user: ${error}`)
);
logger.silly(
`[Gift] Successfully gifted ${optionAmount} credits to ${optionUser.tag}`
);
return interaction.editReply({ return interaction.editReply({
embeds: [ embeds: [
@ -231,6 +247,5 @@ export default {
.setColor(successColor), .setColor(successColor),
], ],
}); });
});
}, },
}; };

View file

@ -1,15 +1,14 @@
// Dependencies // Dependencies
import { CommandInteraction, MessageEmbed, Permissions } from "discord.js"; import { CommandInteraction, MessageEmbed, Permissions } from "discord.js";
import mongoose from "mongoose";
// Configurations // Configurations
import getEmbedConfig from "../../../../../../helpers/getEmbedConfig"; import getEmbedConfig from "../../../../../../helpers/getEmbedConfig";
// Handlers // Handlers
import logger from "../../../../../../logger"; import logger from "../../../../../../logger";
// Helpers
import saveUser from "../../../../../../helpers/saveUser";
// Models // Models
import fetchUser from "../../../../../../helpers/fetchUser"; import fetchUser from "../../../../../../helpers/fetchUser";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders"; import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
@ -193,15 +192,44 @@ export default {
}); });
} }
// Withdraw amount from fromUser const session = await mongoose.startSession();
session.startTransaction();
try {
// Withdraw amount from fromUserDB
fromUser.credits -= optionAmount; fromUser.credits -= optionAmount;
// Deposit amount to toUser // Deposit amount to toUserDB
toUser.credits += optionAmount; toUser.credits += optionAmount;
// Save users await fromUser.save();
await saveUser(fromUser, toUser)?.then(async () => {
logger?.silly(`Saved users`); await toUser.save();
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
session.endSession();
logger.error(`${error}`);
return interaction.editReply({
embeds: [
new MessageEmbed()
.setTitle("[:toolbox:] Manage - Credits (Transfer)")
.setDescription(
"An error occurred while trying to gift credits. Please try again."
)
.setColor(errorColor)
.setTimestamp(new Date())
.setColor(successColor)
.setFooter({ text: footerText, iconURL: footerIcon }),
],
});
} finally {
// ending the session
session.endSession();
}
return interaction?.editReply({ return interaction?.editReply({
embeds: [ embeds: [
@ -225,6 +253,5 @@ export default {
.setFooter({ text: footerText, iconURL: footerIcon }), .setFooter({ text: footerText, iconURL: footerIcon }),
], ],
}); });
});
}, },
}; };