Skip to content

Commit b5ccba7

Browse files
committed
cache home xhr responses
credits @jas14: lichess-org#2372
1 parent d85c6d2 commit b5ccba7

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/http.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,30 @@ function request<T>(url: string, type: 'json' | 'text', opts?: RequestOpts, feed
155155
})
156156
}
157157

158+
type ExpiringCacheEntry = { expires: ReturnType<DateConstructor['now']>, data: any }
159+
const responseCache = new Map<string, ExpiringCacheEntry>()
160+
161+
async function getFromCacheOr<T>(cacheKey: string, cacheSeconds: number, getData: () => Promise<T>): Promise<T> {
162+
const cacheEntry = responseCache.get(cacheKey)
163+
if (cacheEntry && cacheEntry.expires >= Date.now()) {
164+
return cacheEntry.data as T
165+
} else {
166+
responseCache.delete(cacheKey)
167+
}
168+
169+
const newExpirationTime = Date.now() + (cacheSeconds * 1000)
170+
return getData().then((data: T) => {
171+
responseCache.set(cacheKey, {expires: newExpirationTime, data: data})
172+
return data
173+
})
174+
}
175+
176+
export function fetchCachedJSON<T>(cacheSeconds: number, url: string, opts?: RequestOpts, feedback = false): Promise<T> {
177+
return getFromCacheOr(url, cacheSeconds, () => {
178+
return request<T>(url, 'json', opts, feedback)
179+
})
180+
}
181+
158182
export function fetchJSON<T>(url: string, opts?: RequestOpts, feedback = false): Promise<T> {
159183
return request<T>(url, 'json', opts, feedback)
160184
}

src/ui/home/homeXhr.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { fetchJSON } from '../../http'
1+
import { fetchCachedJSON } from '../../http'
22
import { Streamer } from '../../lidraughts/interfaces'
33
import { PuzzleData } from '../../lidraughts/interfaces/training'
44
import { TournamentListItem } from '../../lidraughts/interfaces/tournament'
@@ -8,13 +8,13 @@ interface FeaturedTournamentData {
88
}
99

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

1414
export function dailyPuzzle(): Promise<PuzzleData> {
15-
return fetchJSON('/training/daily', undefined)
15+
return fetchCachedJSON(60, '/training/daily', undefined)
1616
}
1717

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

0 commit comments

Comments
 (0)