diff --git a/app/api/tmdb/[...path]/route.ts b/app/api/tmdb/[...path]/route.ts index 3c53c49..cc829b0 100644 --- a/app/api/tmdb/[...path]/route.ts +++ b/app/api/tmdb/[...path]/route.ts @@ -16,7 +16,7 @@ export async function GET({ nextUrl: { searchParams } }: NextRequest, { params: 'Content-Type': 'application/json', Authorization: `Bearer ${MOVIE_DB_TOKEN}` }, - next: searchParams.get('session_id') ? undefined : { revalidate: 3600 } + next: searchParams.get('preventCache') || searchParams.get('session_id') ? undefined : { revalidate: 3600 } }); if (!response.ok) { diff --git a/components/Header/components/User/useAuth.ts b/components/Header/components/User/useAuth.ts index 5ef0c1e..25666ac 100644 --- a/components/Header/components/User/useAuth.ts +++ b/components/Header/components/User/useAuth.ts @@ -1,14 +1,18 @@ import { useEffect, useRef } from 'react'; import { useMutation } from '@tanstack/react-query'; +import sessionMutation from '@/data/mutations/session'; +import tokenMutation from '@/data/mutations/token'; import { useSetSession } from '@/hooks/useSession'; - -import { createRequestToken, createSession } from '../../../../data'; +import { useToast } from '@/hooks/useToast'; const useAuth = () => { const setSession = useSetSession(); const tabRef = useRef(null); const intervalRef = useRef(); + const retryRef = useRef(10); + + const { toast } = useToast(); useEffect(() => { const interval = intervalRef.current; @@ -16,17 +20,28 @@ const useAuth = () => { }, []); const session = useMutation({ - mutationFn: createSession, + ...sessionMutation(), onSuccess({ session_id }) { setSession(session_id); clearInterval(intervalRef.current); tabRef.current?.close(); + }, + onError() { + if (!retryRef.current) { + toast({ title: 'Authorization failed', description: 'Try to authorize later' }); + + tabRef.current?.close(); + + return clearInterval(intervalRef.current); + } + + retryRef.current--; } }); const requestToken = useMutation({ - mutationFn: createRequestToken, + ...tokenMutation(), onMutate() { tabRef.current = window.open('', '_blank'); tabRef.current?.focus(); diff --git a/data/clients/Http.ts b/data/clients/Http.ts index 9494767..7cd9353 100644 --- a/data/clients/Http.ts +++ b/data/clients/Http.ts @@ -25,17 +25,23 @@ class Http { body?: B; preventCache?: boolean; }): Promise { - const serializedParams = new URLSearchParams( + const searchParams = new URLSearchParams( Object.entries(search ?? {}).reduce((params, [key, value]) => { if (value != null && value !== '') { params.set(key, String(value)); } return params; }, new URLSearchParams()) - ).toString(); + ); + + if (preventCache) { + searchParams.append('preventCache', '1'); + } + + const searchParamsString = searchParams.toString(); try { - const response = await fetch(`${base}${url}${serializedParams ? `?${serializedParams}` : ''}`, { + const response = await fetch(`${base}${url}${searchParamsString ? `?${searchParamsString}` : ''}`, { method, headers: { Authorization: this.authorization || '', diff --git a/data/clients/movieDB.ts b/data/clients/movieDB.ts deleted file mode 100644 index ca48f9b..0000000 --- a/data/clients/movieDB.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN } from '@/env'; - -import Http from './Http'; - -const movieDB = new Http(MOVIE_DB_API_URL, `Bearer ${MOVIE_DB_TOKEN}`); - -export default movieDB; diff --git a/data/index.ts b/data/index.ts deleted file mode 100644 index f49ce2d..0000000 --- a/data/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -'use server'; - -import { cookies } from 'next/headers'; - -import movieDB from './clients/movieDB'; - -export const session = async () => cookies().get('session')?.value; - -export const createRequestToken = async () => { - return movieDB.get('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({ - redirectUrl: `https://www.themoviedb.org/authenticate/${request_token}`, - requestToken: request_token - })); -}; - -export const createSession = async ({ requestToken }: { requestToken: string }) => { - return movieDB.post('/authentication/session/new', { - params: { request_token: requestToken }, - preventCache: true - }); -}; diff --git a/data/mutations/session.ts b/data/mutations/session.ts new file mode 100644 index 0000000..a32289a --- /dev/null +++ b/data/mutations/session.ts @@ -0,0 +1,14 @@ +import movieAdvisor from '../clients/movieAdvisor'; + +const sessionMutation = () => ({ + mutationFn: ({ requestToken }: { requestToken: string }) => + movieAdvisor.post( + '/authentication/session/new', + { + preventCache: true + }, + { request_token: requestToken } + ) +}); + +export default sessionMutation; diff --git a/data/mutations/token.ts b/data/mutations/token.ts new file mode 100644 index 0000000..869f86f --- /dev/null +++ b/data/mutations/token.ts @@ -0,0 +1,11 @@ +import movieAdvisor from '../clients/movieAdvisor'; + +const tokenMutation = () => ({ + mutationFn: () => + movieAdvisor.get('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({ + redirectUrl: `https://www.themoviedb.org/authenticate/${request_token}`, + requestToken: request_token + })) +}); + +export default tokenMutation;