From 3970ce50cbca6bad8c70d093504784908ad41548 Mon Sep 17 00:00:00 2001 From: Kevin Wu Date: Thu, 4 Jan 2024 20:44:32 -0800 Subject: [PATCH] feat: make sure cache <= 30 minutes --- components/search/query-db.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/components/search/query-db.ts b/components/search/query-db.ts index 89a6858..80b799a 100644 --- a/components/search/query-db.ts +++ b/components/search/query-db.ts @@ -1,13 +1,20 @@ import { CollegeObject } from "./Search"; -const cache: Record = {}; +const cache: Record = {}; export async function queryDatabase( university: string, ge: string, ): Promise { - 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); @@ -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) {