vbv/client/src/stores/learningPath.ts

94 lines
2.5 KiB
TypeScript

import { itGetCached } from "@/fetchHelpers";
import { LearningPath } from "@/services/learningPath";
import { useCompletionStore } from "@/stores/completion";
import { useCourseSessionsStore } from "@/stores/courseSessions";
import { useUserStore } from "@/stores/user";
import type { CourseCompletion } from "@/types";
import cloneDeep from "lodash/cloneDeep";
import { defineStore } from "pinia";
export type LearningPathStoreState = {
learningPaths: Map<string, LearningPath>;
page: "INDEX" | "OVERVIEW";
};
type LearningPathKey = string;
function getLearningPathKey(
slug: string,
userId: string | number | undefined
): LearningPathKey {
return `${slug}-${userId}`;
}
export const useLearningPathStore = defineStore({
id: "learningPath",
state: () => {
return {
learningPaths: new Map<LearningPathKey, LearningPath>(),
page: "INDEX",
loading: false,
} as LearningPathStoreState;
},
getters: {
learningPathForUser: (state) => {
return (courseSlug: string, userId: string | number | undefined) => {
if (state.learningPaths.size > 0) {
const learningPathKey = getLearningPathKey(`${courseSlug}-lp`, userId);
return state.learningPaths.get(learningPathKey);
}
return undefined;
};
},
},
actions: {
async loadLearningPath(
slug: string,
userId: number | undefined = undefined,
reload = false,
fail = true
) {
if (!userId) {
const userStore = useUserStore();
userId = userStore.id;
}
const key = getLearningPathKey(slug, userId);
if (this.learningPaths.has(key) && !reload) {
return this.learningPaths.get(key);
}
const learningPathData = await itGetCached(`/api/course/page/${slug}/`);
if (!learningPathData && fail) {
throw `No learning path found with: ${slug}`;
}
const completionStore = useCompletionStore();
let completionData: CourseCompletion[] = [];
if (userId) {
const courseSessionsStore = useCourseSessionsStore();
const courseSession = courseSessionsStore.courseSessionForCourse(
learningPathData.course.slug
);
if (courseSession) {
completionData = await completionStore.loadCompletionData(
courseSession.id,
userId
);
}
}
const learningPath = LearningPath.fromJson(
cloneDeep(learningPathData),
completionData
);
this.learningPaths.set(key, learningPath);
return learningPath;
},
},
});