Skip to content

Commit

Permalink
feat: make sure cache <= 30 minutes
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinWu098 committed Jan 5, 2024
1 parent 1ddccfd commit 3970ce5
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions components/search/query-db.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { CollegeObject } from "./Search";

const cache: Record<string, CollegeObject[]> = {};
const cache: Record<string, [Date, CollegeObject[]]> = {};

export async function queryDatabase(
university: string,
ge: string,
): Promise<CollegeObject[]> {
if (cache[university + ge]) {
return cache[university + ge];
const cacheKey = university + ge;

if (cache[cacheKey] && cache[cacheKey][0]) {
const [cachedDate, cachedData] = cache[cacheKey];

// If not older than 30 minutes, return cached courses
if ((new Date().getTime() - cachedDate.getTime()) / (1000 * 60) <= 30) {
return cachedData;
}
}

const universityParam = encodeURIComponent(university);
Expand All @@ -23,7 +30,7 @@ export async function queryDatabase(

const data = await response.json();

cache[university + ge] = data.courses;
cache[university + ge] = [new Date(), data.courses];

return data.courses;
} catch (error) {
Expand Down

0 comments on commit 3970ce5

Please sign in to comment.