Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache featured streamer results for 15 seconds #2372

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,30 @@ export function fetchJSON<T>(url: string, opts?: RequestOpts, feedback = false):
return request<T>(url, 'json', opts, feedback)
}

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

export function fetchText(url: string, opts?: RequestOpts, feedback = false): Promise<string> {
return request<string>(url, 'text', opts, feedback)
}
8 changes: 6 additions & 2 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, fetchJSON } from '../../http'
import { Streamer } from '../../lichess/interfaces'
import { PuzzleData } from '../../lichess/interfaces/training'
import { TournamentListItem } from '../../lichess/interfaces/tournament'
Expand All @@ -8,7 +8,11 @@ interface FeaturedTournamentData {
}

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

export function dailyPuzzle(): Promise<PuzzleData> {
Expand Down