mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-08 19:40:11 +08:00
feat: add leaderboard api
This commit is contained in:
1 parent
0d8ab8413a
commit
196187d5c9
2 files changed
+51
-1
No files matched your search
@@ -1,5 +1,12 @@
|
|||||||
import { asyncHandler } from '../../middleware/error.js'
|
import { asyncHandler } from '../../middleware/error.js'
|
||||||
|
import { leaderboard } from '../../models/userManager.js'
|
||||||
|
|
||||||
export default asyncHandler(async (req, res) => {
|
export default asyncHandler(async (req, res) => {
|
||||||
res.json({ message: 'leaderboard' })
|
const users = await leaderboard()
|
||||||
|
const response = users.map((user) => ({
|
||||||
|
username: user.user.username,
|
||||||
|
completedQuests: user.completedQuests,
|
||||||
|
numberOfCompletedQuests: user.numberOfCompletedQuests,
|
||||||
|
}))
|
||||||
|
res.json(response)
|
||||||
})
|
})
|
||||||
@@ -22,3 +22,46 @@ export async function createUser(username, email, { password, socialLogin }) {
|
|||||||
|
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function leaderboard() {
|
||||||
|
return UserProfile.aggregate([
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
user: true, // Include the user field in the projection
|
||||||
|
completedQuests: {
|
||||||
|
$map: {
|
||||||
|
input: {
|
||||||
|
$filter: {
|
||||||
|
input: { $objectToArray: '$progress' }, // Convert the progress map to an array
|
||||||
|
as: 'prog',
|
||||||
|
cond: { $eq: ['$$prog.v.completed', true] }, // Filter for completed quests
|
||||||
|
},
|
||||||
|
},
|
||||||
|
as: 'completedProg',
|
||||||
|
in: '$$completedProg.k', // Extract the quest IDs
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$addFields: {
|
||||||
|
numberOfCompletedQuests: { $size: '$completedQuests' }, // Calculate the size of the completedQuests array
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
numberOfCompletedQuests: { $gt: 0 }, // Filter out users who haven't completed any quests
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ $sort: { numberOfCompletedQuests: -1 } },
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'users',
|
||||||
|
localField: 'user',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'user',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ $unwind: '$user' },
|
||||||
|
])
|
||||||
|
}
|
||||||
Reference in new issue
Block a user