Skip to content

Commit

Permalink
cache home xhr responses
Browse files Browse the repository at this point in the history
  • Loading branch information
RoepStoep committed Sep 27, 2023
1 parent d85c6d2 commit b5ccba7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
24 changes: 24 additions & 0 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ function request<T>(url: string, type: 'json' | 'text', opts?: RequestOpts, feed
})
}

type ExpiringCacheEntry = { expires: ReturnType<DateConstructor['now']>, data: any }
const responseCache = new Map<string, ExpiringCacheEntry>()

async function getFromCacheOr<T>(cacheKey: string, cacheSeconds: number, getData: () => Promise<T>): Promise<T> {
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<T>(cacheSeconds: number, url: string, opts?: RequestOpts, feedback = false): Promise<T> {
return getFromCacheOr(url, cacheSeconds, () => {
return request<T>(url, 'json', opts, feedback)
})
}

export function fetchJSON<T>(url: string, opts?: RequestOpts, feedback = false): Promise<T> {
return request<T>(url, 'json', opts, feedback)
}
Expand Down
8 changes: 4 additions & 4 deletions src/ui/home/homeXhr.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchJSON } from '../../http'
import { fetchCachedJSON } from '../../http'
import { Streamer } from '../../lidraughts/interfaces'
import { PuzzleData } from '../../lidraughts/interfaces/training'
import { TournamentListItem } from '../../lidraughts/interfaces/tournament'
Expand All @@ -8,13 +8,13 @@ interface FeaturedTournamentData {
}

export function featuredStreamers(): Promise<readonly Streamer[]> {
return fetchJSON('/api/streamer/featured', undefined)
return fetchCachedJSON(15, '/api/streamer/featured', undefined)
}

export function dailyPuzzle(): Promise<PuzzleData> {
return fetchJSON('/training/daily', undefined)
return fetchCachedJSON(60, '/training/daily', undefined)
}

export function featuredTournaments(): Promise<FeaturedTournamentData> {
return fetchJSON('/tournament/featured', undefined)
return fetchCachedJSON(30, '/tournament/featured', undefined)
}

0 comments on commit b5ccba7

Please sign in to comment.