All files / Rindu/utils/spotifyCalls refreshAccessToken.ts

25% Statements 2/8
0% Branches 0/2
0% Functions 0/1
25% Lines 2/8

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                  42x               4x                                              
import type { ServerApiContext } from "types/serverContext";
import {
  ACCESS_TOKEN_COOKIE,
  getSiteUrl,
  handleJsonResponse,
  makeCookie,
  REFRESH_TOKEN_COOKIE,
  removeTokensFromCookieServer,
  takeCookie,
} from "utils";
 
export interface IRefreshAccessTokenResponse {
  access_token: string;
  refresh_token: string;
  expires_in: string;
}
 
export async function refreshAccessToken(
  context?: ServerApiContext
): Promise<void> {
  const refreshToken = takeCookie(REFRESH_TOKEN_COOKIE, context);
  const response = await fetch(`${getSiteUrl()}/api/spotify-refresh`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ refreshToken }),
  });
  const data = await handleJsonResponse<IRefreshAccessTokenResponse>(response);
 
  if (data) {
    makeCookie({
      name: ACCESS_TOKEN_COOKIE,
      value: data.access_token,
      context,
    });
  } else {
    removeTokensFromCookieServer(context?.res);
  }
}