Skip to content

Commit

Permalink
fix: ✨ throw error if user tries to execute same command while one is…
Browse files Browse the repository at this point in the history
… processing

If a user tries to execute same command twice at same time, then throw error on one of them to prevent them from go around the cooldown system
  • Loading branch information
VermiumSifell committed Jun 2, 2023
1 parent acdd507 commit af14c75
Showing 1 changed file with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import generateCooldownName from "../../../../helpers/generateCooldownName";
import handleCooldown from "./handlers/handleCooldown";
import handleUnavailableCommand from "./handlers/handleUnavailableCommand";

// Create a map to store locks for each identifier (guild ID + user ID + cooldown item)
const commandLocks = new Map();

const cooldownManager = new CooldownManager();

export default async function handleCommandInteraction(
Expand All @@ -24,6 +27,14 @@ export default async function handleCommandInteraction(

try {
const cooldownItem = await generateCooldownName(interaction);

// Check if the identifier is already locked
if (commandLocks.has(cooldownItem)) {
throw new Error(
"You are unable to execute the same command simultaneously."
);
}

const { guildCooldown, userCooldown, guildMemberCooldown } =
await cooldownManager.checkCooldowns(cooldownItem, guild, user);

Expand All @@ -38,10 +49,23 @@ export default async function handleCommandInteraction(
userCooldown,
guildMemberCooldown
);
} else {
await currentCommand.execute(interaction);
return;
}

// Create a promise that represents the current command execution
const commandExecutionPromise = currentCommand.execute(interaction);

// Acquire the lock for the identifier and store the command execution promise
commandLocks.set(cooldownItem, commandExecutionPromise);

// Wait for the current command execution to complete
await commandExecutionPromise;
} catch (error) {
await interactionErrorHandler(interaction, error);
} finally {
const cooldownItem = await generateCooldownName(interaction);

// Release the lock for the identifier
commandLocks.delete(cooldownItem);
}
}

0 comments on commit af14c75

Please sign in to comment.