Skip to content

Commit

Permalink
perf(cache): add redis cache on spotify service
Browse files Browse the repository at this point in the history
  • Loading branch information
wouterds committed Feb 12, 2025
1 parent 5afacbc commit c80a6c3
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions src/lib/spotify.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { Buffer } from 'node:buffer';
import { addSeconds, getUnixTime, isPast } from 'date-fns';

import { AuthTokens } from '~/database';
import { Cache } from '~/lib/cache.server';
import { md5 } from '~/lib/crypto.server';

const CACHE_TTL_MINUTES = 1;

export class Spotify {
private _refreshToken: string | null;
Expand Down Expand Up @@ -150,6 +154,12 @@ export class Spotify {
}

public async getCurrentlyPlaying() {
const cacheKey = 'spotify.currently-playing';
const cached = await Cache.get(cacheKey);
if (cached) {
return cached;
}

const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
headers: { Authorization: `Bearer ${await this.accessToken}` },
});
Expand All @@ -158,10 +168,24 @@ export class Spotify {
return null;
}

return response.json().then(({ item }: { item: SpotifyRawDataTrack }) => mapSong(item));
const song = await response
.json()
.then(({ item }: { item: SpotifyRawDataTrack }) => mapSong(item));

if (song) {
await Cache.set(cacheKey, song, CACHE_TTL_MINUTES * 60);
}

return song;
}

public async getRecentlyPlayed(tracks = 3) {
const cacheKey = `spotify.recently-played:${md5(tracks.toString())}`;
const cached = await Cache.get(cacheKey);
if (cached) {
return cached;
}

const params = new URLSearchParams({});
if (tracks) params.append('limit', tracks.toString());

Expand All @@ -173,11 +197,14 @@ export class Spotify {
return [];
}

return response
const songs = await response
.json()
.then((songs: { items: Array<{ track: SpotifyRawDataTrack; played_at: string }> }) =>
songs.items.map(({ track, played_at }) => mapSong(track, played_at)),
);

await Cache.set(cacheKey, songs, CACHE_TTL_MINUTES * 60);
return songs;
}
}

Expand Down

0 comments on commit c80a6c3

Please sign in to comment.