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

fix: prevent cache to be cleared, if all plans are older than 14 days #253

Merged
merged 2 commits into from
Jul 30, 2024
Merged
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
26 changes: 23 additions & 3 deletions src/lib/cache/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,35 @@ export function clearCache(): void {
/**
* Removes all plans that are older than the given amount of days
* @param {number} days The amount of days
* @param {Date[]} holidays The holidays to exclude, defaults to []
* @returns {void}
*/
export function removeStale(days: number): void {
export function removeStale(days: number, holidays: Date[] = []): void {
const cache = getCache();
const now = new Date();
const startDate = now;

// Check if today is a holiday or weekend
const isHoliday = holidays.some((holiday) => holiday.toDateString() === now.toDateString());
const isWeekend = now.getDay() === 0 || now.getDay() === 6;

if (isHoliday || isWeekend) {
// Find the most recent school day
do {
startDate.setDate(startDate.getDate() - 1);
} while (
holidays.some((holiday) => holiday.toDateString() === startDate.toDateString()) ||
startDate.getDay() === 0 ||
startDate.getDay() === 6
);
}

for (const schoolnumber in cache) {
cache[schoolnumber] = cache[schoolnumber].filter((plan) => {
cache[schoolnumber] = cache[schoolnumber].filter((plan, index, array) => {
const date = new Date(plan.date);
return now.getTime() - date.getTime() < 1000 * 60 * 60 * 24 * days;
const isWithinRange = startDate.getTime() - date.getTime() < 1000 * 60 * 60 * 24 * days;
// Ensure at least one plan remains in the cache
return isWithinRange || array.length === 1;
});
}
setCache(cache);
Expand Down