From 6cff1bba7d6be3818547b40cc9965f4b2ba73711 Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Sat, 17 Apr 2021 20:00:14 +0200 Subject: Cache requests by the hour --- index.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/index.ts b/index.ts index 5bf62c7..830692b 100644 --- a/index.ts +++ b/index.ts @@ -27,6 +27,15 @@ window.onload = function() { } } +const cache = { + added: 0, + value: {} as QueryResponse, + set(data: QueryResponse) { + cache.value = data; + cache.added = +new Date(); + } +} + async function getRepositories(): Promise { const response = await fetch(API_URL, { method: "POST", @@ -52,7 +61,17 @@ async function getRepositories(): Promise { }) if (response.ok) { - const json = await response.json() as QueryResponse; + let json + + if (cache.added < (+new Date() - 3.6E6)) { // cached for 1 hour + json = await response.json() as QueryResponse; + cache.set(json); + console.log("from api"); + } else { + json = cache.value; + console.log("from cache"); + } + return json?.data.repositories.results?.filter(repo => repo.visibility === "PUBLIC") ?? []; } else { throw response; -- cgit v1.3