harden database interactions and improve error handling

This commit is contained in:
ImBenji
2026-04-28 17:05:48 +01:00
parent e1f168a302
commit b9f7d1ff25
16 changed files with 980 additions and 159 deletions
+1 -9
View File
@@ -1,5 +1,5 @@
import { db } from "../../../db/index";
import { courses, topics, userProgress, lessons } from "../../../db/schema";
import { courses, topics, lessons } from "../../../db/schema";
import { eq, inArray } from "drizzle-orm";
export default defineEventHandler(async (event) => {
@@ -16,13 +16,6 @@ export default defineEventHandler(async (event) => {
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
@@ -37,7 +30,6 @@ export default defineEventHandler(async (event) => {
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,
})),
+9 -18
View File
@@ -1,6 +1,6 @@
import { db } from "../../db/index";
import { courses, topics, userProgress } from "../../db/schema";
import { eq, inArray } from "drizzle-orm";
import { courses, topics } from "../../db/schema";
import { inArray } from "drizzle-orm";
export default defineEventHandler(async () => {
const allCourses = await db.query.courses.findMany({
@@ -11,27 +11,18 @@ export default defineEventHandler(async () => {
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) }),
]);
const allTopics = await db.query.topics.findMany({ where: inArray(topics.courseId, courseIds) });
// group in memory
const topicsByCourse = new Map<string, number>();
const topicsByCourse = new Map<string, string[]>();
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);
}
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) ?? 0,
completedCount: completedByCourse.get(course.id) ?? 0,
topicCount: topicsByCourse.get(course.id)?.length ?? 0,
topicIds: topicsByCourse.get(course.id) ?? [],
}));
});