Skip to content

Commit

Permalink
refactor: badge acquiring logic (#280)
Browse files Browse the repository at this point in the history
* refactor: badge acquiring logic

* Update user.ts
  • Loading branch information
3LL4N authored Dec 15, 2023
1 parent 8a899b1 commit 341c6c4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
19 changes: 11 additions & 8 deletions packages/api/src/functions/pointsBadgeHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
export const getPointsBadge = (points: number) => {
const badges = [];
if (points >= 100000) {
return "gold";
} else if (points >= 50000) {
return "silver";
} else if (points >= 20000) {
return "bronze";
badges.push("gold");
}
return "";
if (points >= 50000) {
badges.push("silver");
}
if (points >= 20000) {
badges.push("bronze");
}
return badges;
};

export const verifyAcquiredPointsBadge = (
badgeName: string,
badgeNames: string[],
currentBadges: string[],
) => {
return badgeName !== "" && !currentBadges.includes(badgeName);
return badgeNames.filter((badge) => !currentBadges.includes(badge));
};
16 changes: 11 additions & 5 deletions packages/api/src/router/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,22 +252,28 @@ export const useRouter = router({

const currentBadges = userBadges?.badges ?? [];

const passedBadge = getPointsBadge(totalPoints);
const eligibleBadges = getPointsBadge(totalPoints);

const hasNewBadge = verifyAcquiredPointsBadge(passedBadge, currentBadges);
const newBadges = verifyAcquiredPointsBadge(
eligibleBadges,
currentBadges,
);

if (hasNewBadge) {
if (newBadges.length > 0) {
await ctx.prisma.user.update({
where: {
userId: ctx.auth.userId,
},
data: {
badges: [...currentBadges, ...[passedBadge]],
badges: [...currentBadges, ...newBadges],
},
});
}

return { hasNewBadge: hasNewBadge, acquiredBadge: passedBadge };
return {
hasNewBadge: newBadges.length > 0,
acquiredBadge: newBadges.length > 0 ? newBadges[0] : "",
};
}),

updateTotalPoints: protectedProcedure
Expand Down

0 comments on commit 341c6c4

Please sign in to comment.