45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import { db } from "../../../db/index";
|
|
import { courses, topics, userProgress, lessons } from "../../../db/schema";
|
|
import { eq, inArray } from "drizzle-orm";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const id = getRouterParam(event, "id")!;
|
|
|
|
const course = await db.query.courses.findFirst({
|
|
where: eq(courses.id, id),
|
|
});
|
|
|
|
if (!course) throw createError({ statusCode: 404, message: "Course not found" });
|
|
|
|
const topicRows = await db.query.topics.findMany({
|
|
where: eq(topics.courseId, id),
|
|
orderBy: (t, { asc }) => asc(t.order),
|
|
});
|
|
|
|
const progressRows = await db.query.userProgress.findMany({
|
|
where: eq(userProgress.courseId, id),
|
|
});
|
|
|
|
const progressMap: Record<string, typeof progressRows[0]> = {};
|
|
for (const p of progressRows) progressMap[p.topicId] = p;
|
|
|
|
const topicIds = topicRows.map((t) => t.id);
|
|
|
|
const lessonRows = topicIds.length
|
|
? await db.query.lessons.findMany({ where: inArray(lessons.topicId, topicIds) })
|
|
: [];
|
|
|
|
const lessonMap: Record<string, typeof lessonRows[0]> = {};
|
|
for (const l of lessonRows) lessonMap[l.topicId] = l;
|
|
|
|
return {
|
|
...course,
|
|
topics: topicRows.map((t) => ({
|
|
...t,
|
|
prerequisiteTopicIds: JSON.parse(t.prerequisiteTopicIds ?? "[]"),
|
|
progress: progressMap[t.id] ?? null,
|
|
hasLesson: !!lessonMap[t.id],
|
|
lessonCost: lessonMap[t.id]?.costTotal ?? null,
|
|
})),
|
|
};
|
|
});
|