@@ -24,8 +24,49 @@ googleProvider.addScope("email");
2424
2525// fetches all relevant information to create the model
2626async function firebaseToModel ( model ) {
27+ // Load metadata from localStorage
28+ const cachedMetadata = JSON . parse ( localStorage . getItem ( "coursesMetadata" ) ) ;
29+ const firebaseTimestamp = await fetchLastUpdatedTimestamp ( ) ;
30+ // check if up to date
31+ if ( cachedMetadata && cachedMetadata . timestamp === firebaseTimestamp ) {
32+ console . log ( "Using cached courses..." ) ;
33+ let mergedCourses = [ ] ;
34+ for ( let i = 0 ; i < cachedMetadata . parts ; i ++ ) {
35+ const part = JSON . parse ( localStorage . getItem ( `coursesPart${ i } ` ) ) ;
36+ if ( part )
37+ mergedCourses = mergedCourses . concat ( part ) ;
38+ }
39+ model . setCourses ( mergedCourses ) ;
40+ return ;
41+ }
42+
43+ // Fetch if outdated or missing
44+ console . log ( "Fetching courses from Firebase..." ) ;
2745 const courses = await fetchAllCourses ( ) ;
2846 model . setCourses ( courses ) ;
47+ saveCoursesInChunks ( courses , firebaseTimestamp ) ;
48+ }
49+
50+ function saveCoursesInChunks ( courses , timestamp ) {
51+ const parts = 3 ; // Adjust this based on course size
52+ const chunkSize = Math . ceil ( courses . length / parts ) ;
53+
54+ for ( let i = 0 ; i < parts ; i ++ ) {
55+ const chunk = courses . slice ( i * chunkSize , ( i + 1 ) * chunkSize ) ;
56+ localStorage . setItem ( `coursesPart${ i } ` , JSON . stringify ( chunk ) ) ;
57+ }
58+ localStorage . setItem ( "coursesMetadata" , JSON . stringify ( { parts, timestamp } ) ) ;
59+ }
60+
61+ async function updateLastUpdatedTimestamp ( ) {
62+ const timestampRef = ref ( db , "metadata/lastUpdated" ) ;
63+ await set ( timestampRef , Date . now ( ) ) ;
64+ }
65+
66+ async function fetchLastUpdatedTimestamp ( ) {
67+ const timestampRef = ref ( db , "metadata/lastUpdated" ) ;
68+ const snapshot = await get ( timestampRef ) ;
69+ return snapshot . exists ( ) ? snapshot . val ( ) : 0 ;
2970}
3071
3172export function connectToFirebase ( model ) {
@@ -40,6 +81,7 @@ export async function addCourse(course){
4081 return ;
4182 const myRef = ref ( db , `courses/${ course . code } ` ) ;
4283 await set ( myRef , course ) ;
84+ updateLastUpdatedTimestamp ( ) ;
4385}
4486
4587export async function fetchAllCourses ( ) {
0 commit comments