@@ -32,6 +32,16 @@ export function splitSpotifyLibraryIds(ids: string, maxIds?: number): string[] {
3232 return maxIds === undefined ? list : list . slice ( 0 , maxIds )
3333}
3434
35+ /**
36+ * The Spotify URI for an ID, or the value itself when it is already a URI of `type`. A URI of
37+ * another type is rejected, so a track tool never saves or removes an album, say.
38+ */
39+ function toSpotifyUri ( id : string , type : SpotifyLibraryItemType ) : string {
40+ if ( ! id . startsWith ( 'spotify:' ) ) return `spotify:${ type } :${ id } `
41+ if ( id . split ( ':' ) [ 1 ] !== type ) throw new Error ( `"${ id } " is not a Spotify ${ type } URI` )
42+ return id
43+ }
44+
3545/**
3646 * Builds one Save/Remove (`/me/library`) or Check (`/me/library/contains`) URL per 40 Spotify IDs
3747 * of one type. These generic endpoints replace the per-type save, remove, follow, and contains
@@ -44,7 +54,7 @@ function spotifyLibraryUrls(
4454 options : SpotifyLibraryOptions
4555) : string [ ] {
4656 const uris = splitSpotifyLibraryIds ( ids , options . maxIds ) . map ( ( id ) =>
47- encodeURIComponent ( id . startsWith ( 'spotify:' ) ? id : `spotify: ${ type } : ${ id } ` )
57+ encodeURIComponent ( toSpotifyUri ( id , type ) )
4858 )
4959 const base = `https://api.spotify.com/v1${ options . contains ? '/me/library/contains' : '/me/library' } `
5060 const urls : string [ ] = [ ]
@@ -93,15 +103,18 @@ export async function sendRemainingSpotifyLibraryChunks(
93103 const body = ( await response . json ( ) . catch ( ( ) => null ) ) as {
94104 error ?: { message ?: string }
95105 } | null
106+ const reason = body ?. error ?. message ?? `HTTP ${ response . status } `
107+ const handled = method === 'GET' ? 'checked' : 'applied'
108+ const unsent = last < total ? ` IDs ${ last + 1 } -${ total } were not sent.` : ''
96109 throw new Error (
97- `Spotify rejected IDs ${ first } -${ last } : ${
98- body ?. error ?. message ?? `HTTP ${ response . status } `
99- } `
110+ `IDs 1-${ first - 1 } were ${ handled } . Spotify rejected IDs ${ first } -${ last } : ${ reason } .${ unsent } `
100111 )
101112 }
102113 if ( options . contains ) {
103114 const chunk : unknown = await response . json ( )
104- if ( Array . isArray ( chunk ) ) results . push ( ...chunk . map ( Boolean ) )
115+ if ( ! Array . isArray ( chunk ) )
116+ throw new Error ( 'Spotify returned an invalid library check response' )
117+ results . push ( ...chunk . map ( Boolean ) )
105118 }
106119 }
107120 return results
0 commit comments