-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser-progress.ts
53 lines (42 loc) · 1.42 KB
/
user-progress.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"use server";
import db from "@/db/drizzle";
import { getCourseById, getUserProgress } from "@/db/queries";
import { userProgress } from "@/db/schema";
import { auth, currentUser } from "@clerk/nextjs/server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
export const upsertUserProgress = async (courseId: number) => {
const { userId } = await auth();
const user = await currentUser();
if(!userId || !user) {
throw new Error("Unauthorized");
}
const course = await getCourseById(courseId);
if (!course) {
throw new Error("Course not found"); // would be a 404 error if this was an API call
}
// TODO: enable once units and lessons are added
// if (!course.units.length || !course.units[0].lessons.length) {
// throw new Error("Course is empty");
// }
const existingUserProgress = await getUserProgress();
if (existingUserProgress) {
await db.update(userProgress).set({
activeCourseId: courseId,
userName: user.firstName || "User",
userImageSrc: user.imageUrl || "/mascot.svg",
});
revalidatePath("/courses");
revalidatePath("/learn");
redirect("/learn");
}
await db.insert(userProgress).values({
userId,
activeCourseId: courseId,
userName: user.firstName || "User",
userImageSrc: user.imageUrl || "/mascot.svg",
});
revalidatePath("/courses");
revalidatePath("/learn");
redirect("/learn");
}