import { Client, Playlist } from '[email protected]';
import { Paging } from "spotify-types";
type Spotify = {
token: string;
}
const MAX_PLAYLISTS_PER_PAGE = 50; // this is the max limit allowed by the API
export async function main(
spotifyCredentials: Spotify,
playlistName: string,
fetchIntervalMs: number = 1000,
failOnNotFound: boolean = false
): Promise<Playlist | null> {
const client = await Client.create({
token: spotifyCredentials.token,
userAuthorizedToken: true
});
console.log(`Finding playlist with name '${playlistName}'`);
let offset = 0;
while (true) {
const result: Paging<Playlist | null> = await client.fetch('/me/playlists', {
params: {
limit: MAX_PLAYLISTS_PER_PAGE,
offset: offset
}
});
const playlists = result.items.filter((item): item is Playlist => item !== null);
offset += playlists.length;
console.log(`Fetched ${playlists.length} valid (non-null) playlists (${offset} total)`);
for (const playlist of playlists) {
if (playlist.name === playlistName) {
console.log(`Found playlist '${playlist.name}' (id: ${playlist.id})`)
return playlist;
}
}
if (result.items.length < MAX_PLAYLISTS_PER_PAGE) {
break;
}
// wait for a specified interval between calls to avoid being rate limited
await new Promise(res => setTimeout(res, fetchIntervalMs));
}
const errorMessage = `Failed to find playlist with name '${playlistName}'`;
console.error(errorMessage);
if (failOnNotFound) {
throw new Error(errorMessage);
}
return null;
}
Submitted by alec minchington932 473 days ago
import { Client, Playlist } from '[email protected]';
import { Paging } from "spotify-types";
type Spotify = {
token: string;
}
const MAX_PLAYLISTS_PER_PAGE = 50; // this is the max limit allowed by the API
export async function main(
spotifyCredentials: Spotify,
playlistName: string,
fetchIntervalMs: number = 1000,
failOnNotFound: boolean = false
): Promise<Playlist | null> {
const client = await Client.create({
token: spotifyCredentials.token,
userAuthorizedToken: true
});
console.log(`Finding playlist with name '${playlistName}'`);
let offset = 0;
while (true) {
const result: Paging<Playlist | null> = await client.fetch('/me/playlists', {
params: {
limit: MAX_PLAYLISTS_PER_PAGE,
offset: offset
}
});
const playlists = result.items.filter((item): item is Playlist => item !== null);
offset += playlists.length;
console.log(`Fetched ${playlists.length} valid (non-null) playlists (${offset} total)`);
for (const playlist of playlists) {
if (playlist.name === playlistName) {
console.log(`Found playlist '${playlist.name}' (id: ${playlist.id})`)
return playlist;
}
}
if (result.items.length < MAX_PLAYLISTS_PER_PAGE) {
break;
}
// wait for a specified interval between calls to avoid being rate limited
await new Promise(res => setTimeout(res, fetchIntervalMs));
}
const errorMessage = `Failed to find playlist with name '${playlistName}'`;
console.error(errorMessage);
if (failOnNotFound) {
throw new Error(errorMessage);
}
return null;
}
Submitted by alec minchington932 473 days ago