refactor: use questList to calculate total quests and completed

This commit is contained in:
Chen, Tai-Lin committed 2023-12-21 17:58:52 +08:00
1 parent 3b68693177
commit b0e12b2027
2 files changed
+12 -58

No files matched your search

+12 -3
View File
@@ -1,13 +1,22 @@
import { userCount } from '../models/users.js'
import { totalQuests, totalCompleted } from '../models/quests.js'
import { questList } from '../models/quests.js'
// eslint-disable-next-line import/prefer-default-export
export async function homeController(req, res) {
const quests = await questList()
const [totalQuests, totalCompleted] = quests.reduce(
([total, completed], quest) => [
total + quest.started,
completed + quest.completed,
],
[0, 0]
)
const payload = {
title: 'Linux Odyssey Admin',
userCount: await userCount(),
totalQuests: await totalQuests(),
totalCompleted: await totalCompleted(),
totalQuests,
totalCompleted,
}
payload.completedRate =
Math.round((payload.totalCompleted / payload.totalQuests) * 10000) / 100
-55
View File
@@ -2,61 +2,6 @@
/* eslint-disable func-names */
import { UserProfile } from '@linux-odyssey/models'
export function totalQuests() {
return UserProfile.aggregate([
{
$project: {
_id: 0,
progress: { $objectToArray: '$progress' },
},
},
{
$unwind: '$progress',
},
{
$group: {
_id: null,
totalCount: { $sum: 1 },
},
},
]).then((results) => {
if (results.length === 0) {
throw new Error('No documents found')
}
return results[0].totalCount
})
}
export function totalCompleted() {
return UserProfile.aggregate([
{
$project: {
_id: 0,
progress: { $objectToArray: '$progress' },
},
},
{
$unwind: '$progress',
},
{
$match: {
'progress.v.completed': true,
},
},
{
$group: {
_id: null,
totalCount: { $sum: 1 },
},
},
]).then((results) => {
if (results.length === 0) {
throw new Error('No documents found')
}
return results[0].totalCount
})
}
export function questList() {
return UserProfile.aggregate([
{