28 lines
862 B
TypeScript
28 lines
862 B
TypeScript
import { db } from "../../db/index";
|
|
import { courses, topics } from "../../db/schema";
|
|
import { 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 = await db.query.topics.findMany({ where: inArray(topics.courseId, courseIds) });
|
|
|
|
const topicsByCourse = new Map<string, string[]>();
|
|
for (const t of allTopics) {
|
|
const arr = topicsByCourse.get(t.courseId) ?? [];
|
|
arr.push(t.id);
|
|
topicsByCourse.set(t.courseId, arr);
|
|
}
|
|
|
|
return allCourses.map((course) => ({
|
|
...course,
|
|
topicCount: topicsByCourse.get(course.id)?.length ?? 0,
|
|
topicIds: topicsByCourse.get(course.id) ?? [],
|
|
}));
|
|
});
|