All files / Rindu/utils getAllTracksFromPlaylist.ts

13.33% Statements 2/15
0% Branches 0/7
0% Functions 0/2
14.28% Lines 2/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46  43x   3x                                                                                    
import { ITrack } from "types/spotify";
import { ACCESS_TOKEN_COOKIE, isCorruptedTrack, takeCookie } from "utils";
 
export async function getAllTracksFromPlaylist(
  id: string | undefined,
  totalTracks: number,
  isLibrary: boolean
): Promise<ITrack[]> {
  let tracks: ITrack[] = [];
  const limit = isLibrary ? 50 : 100;
  const max = Math.ceil(totalTracks / limit);
  const accessToken = takeCookie(ACCESS_TOKEN_COOKIE);
  for (let i = 0; i < max; i++) {
    const res = await fetch(
      `https://api.spotify.com/v1/${
        !isLibrary ? `playlists/${id ?? ""}` : "me"
      }/tracks?limit=${limit}&offset=${limit * i}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );
 
    const data = (await res.json()) as
      | SpotifyApi.PlaylistTrackResponse
      | undefined;
    const newTracks: ITrack[] | undefined = data?.items?.map(
      ({ track, added_at, is_local }, index) => {
        return {
          ...track,
          corruptedTrack: isCorruptedTrack(track),
          position: limit * i + index,
          added_at,
          is_local,
        };
      }
    );
    Iif (newTracks) {
      tracks = [...tracks, ...newTracks];
    }
  }
  return tracks;
}