Skip to content

Commit

Permalink
refactor(radio): add cache for the fetchSpotifyInfo function
Browse files Browse the repository at this point in the history
  • Loading branch information
vittee committed Jun 17, 2024
1 parent 007906e commit a37c78f
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/radio/src/discord/helpers/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,25 @@ type SpotifyPlaylistInfo = {

type SpotifyInfo = SpotifyTrackInfo | SpotifyArtistInfo | SpotifyUserInfo | SpotifyAlbumInfo | SpotifyPlaylistInfo;

const cache = new Map<string, Promise<SpotifyInfo | undefined>>;

export async function fetchSpotifyInfo(url: string, expectedType?: SpotifyInfo['type']): Promise<SpotifyInfo | undefined> {
if (cache.has(url)) {
return cache.get(url)!;
}

const promise = internal_fetchSpotifyInfo(url, expectedType);

cache.set(url, promise);

promise.finally(() => {
cache.delete(url);
});

return promise;
}

async function internal_fetchSpotifyInfo(url: string, expectedType?: SpotifyInfo['type']): Promise<SpotifyInfo | undefined> {
const res = await axios.get(url, { timeout: 5000 }).catch(() => false as const);

if (res === false || res.status !== 200) {
Expand Down

0 comments on commit a37c78f

Please sign in to comment.