1 | import { Client, Playlist } from '[email protected]'; |
2 | import { Paging } from "spotify-types"; |
3 |
|
4 | type Spotify = { |
5 | token: string; |
6 | } |
7 |
|
8 | const MAX_PLAYLISTS_PER_PAGE = 50; |
9 |
|
10 | export async function main( |
11 | spotifyCredentials: Spotify, |
12 | playlistName: string, |
13 | fetchIntervalMs: number = 1000, |
14 | failOnNotFound: boolean = false |
15 | ): Promise<Playlist | null> { |
16 | const client = await Client.create({ |
17 | token: spotifyCredentials.token, |
18 | userAuthorizedToken: true |
19 | }); |
20 |
|
21 | console.log(`Finding playlist with name '${playlistName}'`); |
22 |
|
23 | let offset = 0; |
24 | while (true) { |
25 | const result: Paging<Playlist | null> = await client.fetch('/me/playlists', { |
26 | params: { |
27 | limit: MAX_PLAYLISTS_PER_PAGE, |
28 | offset: offset |
29 | } |
30 | }); |
31 |
|
32 | const playlists = result.items.filter((item): item is Playlist => item !== null); |
33 |
|
34 | offset += playlists.length; |
35 |
|
36 | console.log(`Fetched ${playlists.length} valid (non-null) playlists (${offset} total)`); |
37 |
|
38 | for (const playlist of playlists) { |
39 | if (playlist.name === playlistName) { |
40 | console.log(`Found playlist '${playlist.name}' (id: ${playlist.id})`) |
41 | return playlist; |
42 | } |
43 | } |
44 |
|
45 | if (result.items.length < MAX_PLAYLISTS_PER_PAGE) { |
46 | break; |
47 | } |
48 |
|
49 | |
50 | await new Promise(res => setTimeout(res, fetchIntervalMs)); |
51 | } |
52 |
|
53 | const errorMessage = `Failed to find playlist with name '${playlistName}'`; |
54 | console.error(errorMessage); |
55 |
|
56 | if (failOnNotFound) { |
57 | throw new Error(errorMessage); |
58 | } |
59 |
|
60 | return null; |
61 | } |
62 |
|