37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
import { db } from "../../db/index";
|
|
import { courses, topics, userProgress } from "../../db/schema";
|
|
import { eq, inArray } from "drizzle-orm";
|
|
|
|
export default defineEventHandler(async () => {
|
|
const allCourses = await db.query.courses.findMany({
|
|
orderBy: (c, { desc }) => desc(c.createdAt),
|
|
});
|
|
|
|
if (allCourses.length === 0) return [];
|
|
|
|
const courseIds = allCourses.map((c) => c.id);
|
|
|
|
const [allTopics, allProgress] = await Promise.all([
|
|
db.query.topics.findMany({ where: inArray(topics.courseId, courseIds) }),
|
|
db.query.userProgress.findMany({ where: inArray(userProgress.courseId, courseIds) }),
|
|
]);
|
|
|
|
// group in memory
|
|
const topicsByCourse = new Map<string, number>();
|
|
for (const t of allTopics) {
|
|
topicsByCourse.set(t.courseId, (topicsByCourse.get(t.courseId) ?? 0) + 1);
|
|
}
|
|
|
|
const completedByCourse = new Map<string, number>();
|
|
for (const p of allProgress) {
|
|
if (p.lessonComplete) {
|
|
completedByCourse.set(p.courseId, (completedByCourse.get(p.courseId) ?? 0) + 1);
|
|
}
|
|
}
|
|
|
|
return allCourses.map((course) => ({
|
|
...course,
|
|
topicCount: topicsByCourse.get(course.id) ?? 0,
|
|
completedCount: completedByCourse.get(course.id) ?? 0,
|
|
}));
|
|
});
|