From 7a5ac31bfc49955dfe4fa34477c2ae60204c1330 Mon Sep 17 00:00:00 2001 From: Kevin Wu Date: Thu, 4 Jan 2024 21:06:19 -0800 Subject: [PATCH] feat: add cache (#40) * feat: disable PWA in dev * feat: add caching * --amend * feat: make sure cache <= 30 minutes * refactor: use cacheKey --- components/search/Search.tsx | 8 ++++---- components/search/query-db.ts | 25 +++++++++++++++++++++++-- next.config.js | 13 +++++++------ 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/components/search/Search.tsx b/components/search/Search.tsx index dbf4ed9..37a1e1a 100644 --- a/components/search/Search.tsx +++ b/components/search/Search.tsx @@ -164,9 +164,9 @@ const Search = () => { try { const universityParam = university; const geParam = !ge.includes("GE") ? ge : ge.split(" ")[1]; - const data = await queryDatabase(universityParam, geParam); + const courses = await queryDatabase(universityParam, geParam); - setCourses(data.courses); + setCourses(courses); setLoading(false); setError(false); @@ -287,7 +287,7 @@ const Search = () => { searchGE={ge} />
-
+
Search Filters
@@ -317,7 +317,7 @@ const Search = () => {
-
+
Sort By:
= {}; + +export async function queryDatabase( + university: string, + ge: string, +): Promise { + 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); const geParam = encodeURIComponent(ge); @@ -11,7 +29,10 @@ export async function queryDatabase(university: string, ge: string) { } const data = await response.json(); - return data; + + cache[cacheKey] = [new Date(), data.courses]; + + return data.courses; } catch (error) { console.error("Error:", error); throw error; diff --git a/next.config.js b/next.config.js index ba3e418..87a5d0f 100644 --- a/next.config.js +++ b/next.config.js @@ -1,13 +1,14 @@ /** @type {import('next').NextConfig} */ const runtimeCaching = require("next-pwa/cache"); -const withPWA = require('next-pwa')({ - dest: 'public', +const withPWA = require("next-pwa")({ + dest: "public", register: true, skipWaiting: true, - runtimeCaching -}) + runtimeCaching, + disable: process.env.NODE_ENV === "DEVELOPMENT", +}); module.exports = withPWA({ - reactStrictMode: false -}) + reactStrictMode: false, +});