Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement 1-Day Caching for getPurchases API Calls #196

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/utiles/appx.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

import {
getAllCoursesAndContentHierarchy,
getAllVideos,
Expand All @@ -12,7 +13,21 @@ const APPX_CLIENT_SERVICE = process.env.APPX_CLIENT_SERVICE;
const APPX_BASE_API = process.env.APPX_BASE_API;
const LOCAL_CMS_PROVIDER = process.env.LOCAL_CMS_PROVIDER;

// Initialize a simple in-memory cache
const cache = {
purchases: {},
};

const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

export async function getPurchases(email: string) {
const now = Date.now();
// Check if there's cached data for this email and if it's still valid
const cachedEntry = cache.purchases[email];
if (cachedEntry && now - cachedEntry.timestamp < CACHE_DURATION) {
return cachedEntry.data; // return cached data
}

const _courses = await getAllCoursesAndContentHierarchy();
const session = await getServerSession(authOptions);
const userVideoProgress = await getVideoProgressForUser(
Expand All @@ -21,11 +36,10 @@ export async function getPurchases(email: string) {
);
const allVideos = await getAllVideos();

const completedVideosLookup: { [key: string]: boolean } =
userVideoProgress?.reduce((acc: any, progress) => {
acc[progress.contentId] = true;
return acc;
}, {});
const completedVideosLookup = userVideoProgress?.reduce((acc, progress) => {
acc[progress.contentId] = true;
return acc;
}, {});

const courses = _courses.map((course) => {
let totalVideos = 0;
Expand Down Expand Up @@ -55,6 +69,8 @@ export async function getPurchases(email: string) {
});

if (LOCAL_CMS_PROVIDER) {
// Cache result before returning
cache.purchases[email] = { timestamp: now, data: courses };
return courses;
}

Expand All @@ -73,7 +89,6 @@ export async function getPurchases(email: string) {
itemtype: '10',
itemid: course.appxCourseId.toString(),
});
//@ts-ignore
const response = await fetch(`${baseUrl}?${params}`, { headers });
const data = await response.json();

Expand All @@ -91,5 +106,9 @@ export async function getPurchases(email: string) {
}
}
}

// Cache result before returning
cache.purchases[email] = { timestamp: now, data: responses };

return responses;
}