65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
import { supaBrowser as supabase } from "shared/api/supabase";
|
||
import { CourseModule } from "shared/domain/course";
|
||
import { Term } from "shared/domain/term";
|
||
|
||
export async function fetchCourse(courseid: number): Promise<CourseModule | null> {
|
||
const { data, error } = await supabase
|
||
.schema("library")
|
||
.from("mv_course_with_module") // TODO: MAke a better view
|
||
.select("*")
|
||
.eq("course_id", courseid)
|
||
.single();
|
||
|
||
if (error) throw error;
|
||
|
||
return data as CourseModule;
|
||
}
|
||
|
||
export async function fetchCoursesModules(term: Term): Promise<CourseModule[]> {
|
||
const { data, error } = await supabase
|
||
.schema("library")
|
||
.from("mv_course_with_module") // TODO: MAke a better view
|
||
.select("*")
|
||
.eq("semester_id", term.semester_id)
|
||
|
||
const { data: favs, error: favsError } = await supabase
|
||
.schema("library")
|
||
.from("module_favorites")
|
||
.select("module_id, user_uuid")
|
||
.eq("user_uuid", (await supabase.auth.getUser()).data.user?.id);
|
||
|
||
if (!favsError) {
|
||
return data!.map((courseModule) => {
|
||
const is_user_favorite = favs.some(
|
||
(fav) => fav.module_id === courseModule.module_id
|
||
);
|
||
return { ...courseModule, is_user_favorite };
|
||
}) as CourseModule[];
|
||
}
|
||
|
||
if (error) throw error;
|
||
|
||
return data as CourseModule[];
|
||
}
|
||
|
||
/**
|
||
* Toggle the “favorite” flag for the current user.
|
||
* Returns true if the RPC says the row is now a favorite.
|
||
*/
|
||
export async function toggleCourseFavorite(
|
||
courseModule: CourseModule,
|
||
isfavorite: boolean,
|
||
): Promise<boolean> {
|
||
|
||
const { data, error } = await supabase
|
||
.schema("library")
|
||
.rpc("upsert_module_favorites", {
|
||
p_favorite_state: isfavorite,
|
||
p_module_id: courseModule.module_id,
|
||
});
|
||
|
||
if (error) throw error;
|
||
|
||
return data === "true";
|
||
}
|