refactor(token): simplify token deletion and retrieval logic

- Consolidated query conditions for token deletion and retrieval into a single array for improved readability.
- Removed redundant error handling for empty query conditions, as the logic now directly checks for provided parameters.
- Enhanced the return statement for the findToken method to streamline the code structure.
This commit is contained in:
Danny Avila 2025-05-30 14:29:21 -04:00
parent a4c6553695
commit 6f4c8ef114
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956

View file

@ -47,27 +47,13 @@ export function createTokenMethods(mongoose: typeof import('mongoose')) {
async function deleteTokens(query: TokenQuery): Promise<TokenDeleteResult> {
try {
const Token = mongoose.models.Token;
const conditions = [];
if (query.userId) {
conditions.push({ userId: query.userId });
}
if (query.token) {
conditions.push({ token: query.token });
}
if (query.email) {
conditions.push({ email: query.email });
}
if (query.identifier) {
conditions.push({ identifier: query.identifier });
}
if (conditions.length === 0) {
throw new Error('At least one query parameter must be provided');
}
return await Token.deleteMany({
$or: conditions,
$or: [
{ userId: query.userId },
{ token: query.token },
{ email: query.email },
{ identifier: query.identifier },
],
});
} catch (error) {
logger.debug('An error occurred while deleting tokens:', error);
@ -96,13 +82,11 @@ export function createTokenMethods(mongoose: typeof import('mongoose')) {
conditions.push({ identifier: query.identifier });
}
if (conditions.length === 0) {
throw new Error('At least one query parameter must be provided');
}
return (await Token.findOne({
const token = await Token.findOne({
$and: conditions,
}).lean()) as IToken | null;
}).lean();
return token as IToken | null;
} catch (error) {
logger.debug('An error occurred while finding token:', error);
throw error;
@ -111,10 +95,10 @@ export function createTokenMethods(mongoose: typeof import('mongoose')) {
// Return all methods
return {
findToken,
createToken,
updateToken,
deleteTokens,
findToken,
};
}