Skip to content

Commit

Permalink
Add paging support for spotify service
Browse files Browse the repository at this point in the history
  • Loading branch information
pkarpovich committed Oct 21, 2022
1 parent 2dc83e2 commit 8ae5514
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-ducks-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'playlist-synchronizer': patch
---

Add paging support for spotify service
33 changes: 24 additions & 9 deletions src/services/music-providers/spotify.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ConfigService } from '../config.service.js';
import { LogService } from '../log.service.js';
import { AuthStore, Playlist, Track } from '../../entities.js';
import { IConfig } from '../../config.js';
import { retry } from '../../utils.js';
import { parseUrlToQueryParams, retry } from '../../utils.js';

const scopes = [
'playlist-read-private',
Expand Down Expand Up @@ -73,14 +73,29 @@ export class SpotifyService implements BaseMusicService {
}

async getPlaylistTracks({ id }: Playlist): Promise<Track[]> {
const { body } = await retry<
Response<SpotifyApi.PlaylistTrackResponse>
>(
() => this.client.getPlaylistTracks(id),
() => this.refreshAccess(),
);

return body.items.map<Track>(({ track }) => ({
const items: SpotifyApi.PlaylistTrackObject[] = [];
let nextPage: string | null = null;

do {
const { limit, offset } = nextPage
? parseUrlToQueryParams(nextPage)
: { limit: 100, offset: 0 };

const resp: Response<SpotifyApi.PlaylistTrackResponse> =
await retry<Response<SpotifyApi.PlaylistTrackResponse>>(
() =>
this.client.getPlaylistTracks(id, {
limit: Number(limit),
offset: Number(offset),
}),
() => this.refreshAccess(),
);

items.push(...resp.body.items);
nextPage = resp.body.next;
} while (nextPage);

return items.map<Track>(({ track }) => ({
id: track?.uri,
name: track?.name as string,
artists: track?.artists.map(({ name }) => name) as string[],
Expand Down
1 change: 1 addition & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './utils/cleanup.js';
export * from './utils/retry.js';
export * from './utils/url.js';
5 changes: 5 additions & 0 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { URL } from 'node:url';

export function parseUrlToQueryParams(url: string): Record<string, string> {
return Object.fromEntries(new URL(url).searchParams);
}

0 comments on commit 8ae5514

Please sign in to comment.