-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathachievementcheck.js
55 lines (46 loc) · 1.88 KB
/
achievementcheck.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const achievements = require('./achievements'); // Import achievements
const notificationController = require('../controllers/notificationcontroller'); // Notifications
// Function to check and award achievements
async function checkAchievements(user) {
try {
if (!user) {
throw new Error('User object is required');
}
// Track newly unlocked achievements
const newAchievements = [];
// Iterate through all achievements
achievements.forEach((achievement) => {
// Check if the achievement is already unlocked
const alreadyUnlocked = user.achievements.some(
(ach) => ach.id === achievement.id
);
// Unlock if conditions are met and not already unlocked
if (!alreadyUnlocked && achievement.condition(user)) {
// Add achievement to user's list
const unlockedAchievement = {
id: achievement.id,
title: achievement.title,
description: achievement.description,
unlockedAt: new Date(),
};
user.achievements.push(unlockedAchievement);
newAchievements.push(unlockedAchievement);
// Send notification for unlocked achievement
notificationController.createNotification(
user.id,
`Achievement unlocked: ${achievement.title} - ${achievement.description}`,
'achievement'
);
}
});
// Save the user only if new achievements were unlocked
if (newAchievements.length > 0) {
await user.save();
}
return newAchievements;
} catch (error) {
console.error('Error checking achievements:', error);
throw error;
}
}
module.exports = checkAchievements;