diff --git a/src/http.ts b/src/http.ts index 7753ab306d..3caa49b877 100644 --- a/src/http.ts +++ b/src/http.ts @@ -159,6 +159,30 @@ export function fetchJSON(url: string, opts?: RequestOpts, feedback = false): return request(url, 'json', opts, feedback) } +type ExpiringCacheEntry = {expires: ReturnType, data: any} +const responseCache = new Map() + +async function getFromCacheOr(cacheKey: string, cacheSeconds: number, getData: () => Promise): Promise { + const cacheEntry = responseCache.get(cacheKey) + if (cacheEntry && cacheEntry.expires >= Date.now()) { + return cacheEntry.data as T + } else { + responseCache.delete(cacheKey) + } + + const newExpirationTime = Date.now() + (cacheSeconds * 1000) + return getData().then((data: T) => { + responseCache.set(cacheKey, {expires: newExpirationTime, data: data}) + return data + }) +} + +export function fetchCachedJSON(cacheKey: string, cacheSeconds: number, url: string, opts?: RequestOpts, feedback = false): Promise { + return getFromCacheOr(cacheKey, cacheSeconds, () => { + return request(url, 'json', opts, feedback) + }) +} + export function fetchText(url: string, opts?: RequestOpts, feedback = false): Promise { return request(url, 'text', opts, feedback) } diff --git a/src/ui/home/homeXhr.ts b/src/ui/home/homeXhr.ts index 5358153c3b..2cf1285d2f 100644 --- a/src/ui/home/homeXhr.ts +++ b/src/ui/home/homeXhr.ts @@ -1,4 +1,4 @@ -import { fetchJSON } from '../../http' +import { fetchCachedJSON, fetchJSON } from '../../http' import { Streamer } from '../../lichess/interfaces' import { PuzzleData } from '../../lichess/interfaces/training' import { TournamentListItem } from '../../lichess/interfaces/tournament' @@ -8,7 +8,11 @@ interface FeaturedTournamentData { } export function featuredStreamers(): Promise { - return fetchJSON('/api/streamer/featured', undefined) + return fetchCachedJSON( + 'streamer/featured', + 15, + '/api/streamer/featured', + ) } export function dailyPuzzle(): Promise {