All files / Rindu/utils/spotifyCalls addCustomPlaylistImage.ts

13.63% Statements 3/22
0% Branches 0/8
0% Functions 0/2
16.66% Lines 3/18

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 47 48 49 5042x                   42x                                     6x                                        
import { callSpotifyApi } from "./callSpotifyApi";
import type { ServerApiContext } from "types/serverContext";
 
interface IAddCustomPlaylistImage {
  user_id: string | undefined;
  playlist_id: string | undefined;
  imageId?: string;
  context?: ServerApiContext;
}
 
const getCoverData = (imageId?: string) => {
  const cover: HTMLElement | null = document.getElementById(
    imageId ?? "cover-image"
  );
 
  Iif (!cover) return null;
 
  const canvas = document.createElement("canvas");
  canvas.width = cover.clientWidth;
  canvas.height = cover.clientHeight;
  const ctx = canvas.getContext("2d");
 
  Iif (!ctx) return null;
 
  ctx.drawImage(cover as HTMLImageElement, 0, 0, canvas.width, canvas.height);
  const dataUrl = canvas.toDataURL("image/jpeg");
  return dataUrl.split(",")[1];
};
 
export async function addCustomPlaylistImage({
  user_id,
  playlist_id,
  imageId,
  context,
}: IAddCustomPlaylistImage): Promise<boolean> {
  Iif (!playlist_id || !user_id) return false;
 
  const coverData = getCoverData(imageId);
  Iif (!coverData) return false;
 
  const res = await callSpotifyApi({
    endpoint: `/users/${user_id}/playlists/${playlist_id}/images`,
    method: "PUT",
    context,
    body: coverData,
  });
 
  return res.ok;
}