All files / Rindu/hooks useRefreshAccessToken.ts

19.23% Statements 5/26
0% Branches 0/9
0% Functions 0/4
20.83% Lines 5/24

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 4419x   19x   19x 19x 19x                                                                          
import { useEffect } from "react";
 
import { useRouter } from "next/router";
 
import { useAuth } from "hooks";
import { EXPIRE_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE, takeCookie } from "utils";
import { refreshAccessToken } from "utils/spotifyCalls";
 
export function useRefreshAccessToken(): void {
  const router = useRouter();
  const { user } = useAuth();
 
  useEffect(() => {
    const isLoginPage = router.pathname === "/";
    const isNotFoundPage = router.pathname === "/404";
    const isErrorPage = router.pathname === "/500";
 
    Iif (isNotFoundPage || isErrorPage) return;
    Iif (!user?.uri && !isLoginPage) {
      router.push("/");
      return;
    }
 
    function handleRefreshAccessToken() {
      const refreshToken = takeCookie(REFRESH_TOKEN_COOKIE);
      Iif (!refreshToken) {
        router.push("/");
        return;
      }
 
      refreshAccessToken();
    }
 
    const expireIn = parseInt(takeCookie(EXPIRE_TOKEN_COOKIE) ?? "3600", 10);
 
    const interval = setInterval(
      handleRefreshAccessToken,
      (expireIn - 500) * 1000
    );
 
    return () => clearInterval(interval);
  }, [user?.uri, router]);
}