All files / Rindu/utils/spotifyCalls callSpotifyApi.ts

44.44% Statements 4/9
0% Branches 0/4
0% Functions 0/1
44.44% Lines 4/9

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 4343x   43x 43x                   4x                                                          
import { refreshAccessToken } from "./refreshAccessToken";
import type { ServerApiContext } from "types/serverContext";
import { ACCESS_TOKEN_COOKIE } from "utils/constants";
import { takeCookie } from "utils/cookies";
 
interface ICallSpotifyApi {
  endpoint: string;
  method: string;
  context: ServerApiContext | undefined;
  body?: BodyInit | null;
  retry?: boolean;
}
 
export async function callSpotifyApi({
  endpoint,
  method,
  context,
  body,
  retry,
}: ICallSpotifyApi): Promise<Response> {
  const res = await fetch(`https://api.spotify.com/v1${endpoint}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${takeCookie(ACCESS_TOKEN_COOKIE, context)}`,
    },
    body,
  });
 
  Iif (res.ok && res.status === 401 && !retry) {
    await refreshAccessToken(context);
    return callSpotifyApi({
      endpoint,
      method,
      context,
      body,
      retry: true,
    });
  }
 
  return res;
}