refactoring: server actions data fetching -> api routes

This commit is contained in:
ner committed 2024-10-26 21:33:39 +03:00
1 parent 1111712d2c
commit 5cbf93b3b8
38 files changed
+326 -308

No files matched your search

+6 -5
View File
@@ -1,7 +1,10 @@
type Search = Record<string, string | number | boolean | null | undefined>;
class Http {
private readonly base = 'https://api.themoviedb.org/3';
constructor(
private base: string,
private authorization?: string
) {}
private async request<T, B = unknown>({
method,
@@ -31,7 +34,7 @@ class Http {
const response = await fetch(`${base}${url}?${serializedParams}`, {
method,
headers: {
Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`,
Authorization: this.authorization || '',
'Content-Type': 'application/json'
},
body: body ? JSON.stringify(body) : undefined,
@@ -82,6 +85,4 @@ class Http {
}
}
const http = new Http();
export default http;
export default Http;
+5
View File
@@ -0,0 +1,5 @@
import Http from './Http';
const movieAdvisor = new Http('http://localhost:3000/api/tmdb');
export default movieAdvisor;
+5
View File
@@ -0,0 +1,5 @@
import Http from './Http';
const theMovieDb = new Http('https://api.themoviedb.org/3', `Bearer ${process.env.MOVIE_DB_TOKEN}`);
export default theMovieDb;
+3 -163
View File
@@ -2,13 +2,11 @@
import { cookies } from 'next/headers';
import { createUniqueRandomGenerator } from '@/lib/utils';
import mapMoviesSeriesResponseToShows, { mapMovieSeriesToShow } from './dto/Show';
import mapMoviesSeriesResponseToShows from './dto/Show';
import tlk from './parsers/tlk';
import http from './Http';
import http from './clients/theMovieDb';
const session = () => cookies().get('session')?.value;
export const session = () => cookies().get('session')?.value;
export const createRequestToken = async () => {
return http.get<RequestToken>('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({
@@ -77,162 +75,4 @@ export const usersShows = async ({
.then((response) => mapMoviesSeriesResponseToShows(response, showType));
};
export const search = async ({
query,
page,
type = 'movie'
}: {
query: string;
page: string;
type: Show['type'];
}): Promise<Pagination<Show>> => {
return http
.get<TMDBPagination<Movie>>(`/search/${type}`, {
params: {
query,
page
}
})
.then((response) => mapMoviesSeriesResponseToShows(response, type));
};
const TOTAL_PAGES = 400;
const generatePage = createUniqueRandomGenerator(TOTAL_PAGES);
export const details = async ({
showId,
showType = 'movie'
}: {
showId: Show['id'];
showType: Show['type'];
}): Promise<Show & Details> => {
return http
.get<(Movie | Series) & Details>(`/${showType}/${showId}`)
.then((response) => ({ ...response, ...mapMovieSeriesToShow(response, showType) }));
};
export const randomMovies = async (): Promise<Pagination<Show>> => {
return http
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
'vote_count.gte': 300,
sort_by: 'popularity.desc',
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
page: generatePage()
}
})
.then(mapMoviesSeriesResponseToShows);
};
export const popularByType = async ({ type }: { type: 'streaming' | 'theater' | 'rent' }): Promise<Show[]> => {
const params =
type === 'theater'
? { with_release_type: 3 }
: { with_watch_monetization_types: type === 'streaming' ? 'flatrate' : 'rent' };
return http
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
...params,
watch_region: 'US'
}
})
.then((response) => {
const data = mapMoviesSeriesResponseToShows(response);
return data.results;
});
};
export const popularMovies = async ({ page }: { page?: string } = {}): Promise<Pagination<Show>> => {
return http
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
page,
sort_by: 'popularity.desc',
'vote_count.gte': 300,
'vote_average.lte': 10,
'vote_average.gte': 5
}
})
.then(mapMoviesSeriesResponseToShows);
};
export const trendingMovies = async ({ page }: { page?: string } = {}): Promise<Show[]> => {
return http
.get<TMDBPagination<Movie>>('/trending/movie/day', {
params: {
page
}
})
.then((response) => {
const data = mapMoviesSeriesResponseToShows(response);
return data.results;
});
};
export const topMovies = async ({ page, starring }: { page?: string; starring?: string } = {}): Promise<
Pagination<Show>
> => {
return http
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
page,
with_cast: starring,
with_people: starring,
sort_by: 'vote_average.desc',
'vote_count.gte': 300,
'vote_average.lte': 10,
'vote_average.gte': 5
}
})
.then(mapMoviesSeriesResponseToShows);
};
export const similarShows = async ({
page,
showId,
showType = 'movie'
}: {
page?: string;
showId: string;
showType: Show['type'];
}): Promise<Pagination<Show>> => {
return http
.get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/${showType}/${showId}/recommendations`, {
params: {
page
}
})
.then((response) => mapMoviesSeriesResponseToShows(response, showType));
};
export const credits = async ({
showId,
showType = 'movie'
}: {
showId?: Show['id'];
showType?: Show['type'];
}): Promise<Array<Actor>> => {
return http
.get<{ cast: Array<Actor | AggregatedActor> }>(
`/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`
)
.then(({ cast }) => {
return cast
.filter((person) => person.profile_path)
.map((actor) => {
const photoUrl = `https://image.tmdb.org/t/p/w185${actor.profile_path}`;
if ('character' in actor) return { ...actor, photoUrl };
const [{ character }] = actor.roles || [{}];
return { ...actor, character, photoUrl };
});
});
};
export const fetchTLKMagnet = async (url: string) => tlk.magnet(url);
+21
View File
@@ -0,0 +1,21 @@
import movieAdvisor from '../clients/movieAdvisor';
export type AccountQueryProps = {
session?: string | null;
};
export const KEY = ({ session }: AccountQueryProps) => ['account', session];
const accountQuery = ({ session }: AccountQueryProps) => ({
enabled: Boolean(session),
queryKey: KEY({ session }),
staleTime: Infinity,
notifyOnChangeProps: ['data' as const],
queryFn: () =>
movieAdvisor.get<Account>('/account/null', {
params: { session_id: session },
preventCache: true
})
});
export default accountQuery;
+31
View File
@@ -0,0 +1,31 @@
import movieAdvisor from '../clients/movieAdvisor';
export type CreditsQueryProps = {
showId?: Show['id'];
showType?: Show['type'];
};
const creditsQuery = ({ showId, showType }: CreditsQueryProps) => ({
enabled: Boolean(showId),
queryKey: ['credits', showId, showType],
queryFn: () =>
movieAdvisor
.get<{ cast: Array<Actor | AggregatedActor> }>(
`/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`
)
.then(({ cast }) => {
return cast
.filter((person) => person.profile_path)
.map((actor) => {
const photoUrl = `https://image.tmdb.org/t/p/w185${actor.profile_path}`;
if ('character' in actor) return { ...actor, photoUrl };
const [{ character }] = actor.roles || [{}];
return { ...actor, character, photoUrl };
});
})
});
export default creditsQuery;
+18
View File
@@ -0,0 +1,18 @@
import movieAdvisor from '../clients/movieAdvisor';
import { mapMovieSeriesToShow } from '../dto/Show';
export type DetailsQueryProps = {
showId?: Show['id'];
showType?: Show['type'];
};
const detailsQuery = ({ showId, showType }: DetailsQueryProps) => ({
enabled: Boolean(showId),
queryKey: ['details', showId, showType],
queryFn: () =>
movieAdvisor
.get<(Movie | Series) & Details>(`/${showType}/${showId}`)
.then((response) => ({ ...response, ...mapMovieSeriesToShow(response, showType) }))
});
export default detailsQuery;
+29
View File
@@ -0,0 +1,29 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type PopularQueryProps = {
sortBy?: string;
starring?: string;
};
const popularQuery = ({ sortBy = 'popularity.desc', starring }: PopularQueryProps = {}) => ({
suspense: true,
queryKey: ['popular', sortBy, starring],
initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
page: pageParam,
sort_by: sortBy,
with_cast: starring,
with_people: starring,
'vote_count.gte': 300,
'vote_average.lte': 10,
'vote_average.gte': 5
}
})
.then(mapMoviesSeriesResponseToShows)
});
export default popularQuery;
+26
View File
@@ -0,0 +1,26 @@
import { createUniqueRandomGenerator } from '@/lib/utils';
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
const TOTAL_PAGES = 400;
export const generatePage = createUniqueRandomGenerator(TOTAL_PAGES);
const randomQuery = () => ({
suspense: true,
queryKey: ['random-movie'],
initialPageParam: '1',
queryFn: () =>
movieAdvisor
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
'vote_count.gte': 300,
sort_by: 'popularity.desc',
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
page: generatePage()
}
})
.then(mapMoviesSeriesResponseToShows)
});
export default randomQuery;
+15
View File
@@ -0,0 +1,15 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type SearchQueryProps = { query: string; type: Show['type'] };
const searchQuery = ({ query, type }: SearchQueryProps) => ({
queryKey: ['search', query, type],
queryFn: ({ pageParam }: { pageParam: string }) =>
movieAdvisor
.get<TMDBPagination<Movie>>(`/search/${type}`, { params: { page: pageParam, query } })
.then((response) => mapMoviesSeriesResponseToShows(response, type)),
enabled: Boolean(query)
});
export default searchQuery;
+23
View File
@@ -0,0 +1,23 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type SimilarQueryProps = {
showId: string;
showType: Show['type'];
};
const similarQuery = ({ showId, showType }: SimilarQueryProps) => ({
enabled: Boolean(showId),
queryKey: ['similar', showId, showType],
initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor
.get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/${showType}/${showId}/recommendations`, {
params: {
page: pageParam
}
})
.then((response) => mapMoviesSeriesResponseToShows(response, showType))
});
export default similarQuery;
+37
View File
@@ -0,0 +1,37 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type TrendingQueryProps = {
type: 'trending' | 'streaming' | 'theater';
};
const trendingQuery = ({ type }: TrendingQueryProps) => ({
queryKey: ['trending', `type-${type}`],
queryFn: () => {
const params: Record<string, string | number> = {};
if (type !== 'trending') {
params['watch_region'] = 'US';
}
if (type === 'theater') {
params['with_release_type'] = 3;
}
if (type === 'streaming') {
params['with_watch_monetization_types'] = 'flatrate';
}
return movieAdvisor
.get<TMDBPagination<Movie>>(type === 'trending' ? '/trending/movie/day' : '/discover/movie', {
params
})
.then((response) => {
const data = mapMoviesSeriesResponseToShows(response);
return data.results;
});
}
});
export default trendingQuery;
+25
View File
@@ -0,0 +1,25 @@
import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type UsersShowsQueryProps = {
showType: Show['type'];
list: 'favorite' | 'watchlist';
session?: string | null;
};
export const KEY = ({ list, showType, session }: UsersShowsQueryProps) => [`users-${list}`, showType, session];
const usersShowsQuery = ({ showType, list, session }: UsersShowsQueryProps) => ({
suspense: true,
queryKey: KEY({ list, showType, session }),
initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor
.get<TMDBPagination<Movie>>(`/account/null/${list}/${showType === 'tv' ? 'tv' : 'movies'}`, {
params: { page: pageParam, sort_by: 'created_at.desc', session_id: session },
preventCache: true
})
.then((response) => mapMoviesSeriesResponseToShows(response, showType))
});
export default usersShowsQuery;
-2
View File
@@ -1,5 +1,3 @@
'use client';
import UsersList from '@/components/UsersLists';
const Container = () => <UsersList list='favorite' label='favorites' />;
+4 -7
View File
@@ -1,7 +1,8 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { usersShows } from '@/api';
import { session } from '@/api';
import usersShowsQuery from '@/api/queries/usersShows';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -12,17 +13,13 @@ export const metadata: Metadata = {
'View your favorite shows on Movie Advisor. Keep track of films you’ve added and revisit your top picks anytime.'
};
const Favorites = async () => {
const Favorites = () => {
const queryClient = getQueryClient();
const list = 'favorite';
const showType = 'movie';
await queryClient.prefetchInfiniteQuery({
queryKey: [`users-${list}`, showType],
queryFn: () => usersShows({ showType, list, page: '1' }),
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(usersShowsQuery({ showType, list, session: session() }));
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+2 -6
View File
@@ -1,6 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { randomMovies } from '@/api';
import randomQuery from '@/api/queries/random';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -8,11 +8,7 @@ import Container from './container';
const Random = () => {
const queryClient = getQueryClient();
queryClient.prefetchInfiniteQuery({
queryKey: ['random-movie'],
queryFn: randomMovies,
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(randomQuery());
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+2 -6
View File
@@ -1,7 +1,7 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { popularMovies } from '@/api';
import popularQuery from '@/api/queries/popular';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -15,11 +15,7 @@ export const metadata: Metadata = {
const Popular = () => {
const queryClient = getQueryClient();
queryClient.prefetchInfiniteQuery({
queryKey: ['popular'],
queryFn: () => popularMovies(),
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(popularQuery());
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+2 -2
View File
@@ -1,8 +1,8 @@
'use client';
import { popularMovies } from '@/api';
import popularQuery from '@/api/queries/popular';
import useInfiniteList from '@/hooks/useInfiniteList';
const usePopular = () => useInfiniteList({ suspense: true, queryKey: ['popular'], queryFn: popularMovies });
const usePopular = () => useInfiniteList(popularQuery());
export default usePopular;
+2 -6
View File
@@ -1,6 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { similarShows } from '@/api';
import similarQuery from '@/api/queries/similar';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -10,11 +10,7 @@ const Similar = ({ searchParams }: { searchParams: Record<string, string> }) =>
const { id, type } = searchParams || {};
queryClient.prefetchInfiniteQuery({
queryKey: ['similar', id, type],
queryFn: () => similarShows({ showId: id, showType: type as Show['type'] }),
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(similarQuery({ showId: id, showType: type as Show['type'] }));
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+2 -8
View File
@@ -1,6 +1,6 @@
'use client';
import { similarShows } from '@/api';
import similarQuery from '@/api/queries/similar';
import useInfiniteList from '@/hooks/useInfiniteList';
interface Props {
@@ -8,12 +8,6 @@ interface Props {
showType: Show['type'];
}
const useSimilar = ({ showId, showType = 'movie' }: Props) =>
useInfiniteList({
suspense: true,
enabled: Boolean(showId),
queryKey: ['similar', showId, showType],
queryFn: ({ page }) => similarShows({ page, showId, showType })
});
const useSimilar = ({ showId, showType = 'movie' }: Props) => useInfiniteList(similarQuery({ showId, showType }));
export default useSimilar;
+2 -6
View File
@@ -1,6 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { topMovies } from '@/api';
import popularQuery from '@/api/queries/popular';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -10,11 +10,7 @@ const Starring = ({ searchParams }: { searchParams: Record<string, string> }) =>
const { actorId } = searchParams || {};
queryClient.prefetchInfiniteQuery({
queryKey: ['starring', actorId],
queryFn: () => topMovies({ starring: actorId }),
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(popularQuery({ sortBy: 'vote_average.desc', starring: actorId }));
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+2 -7
View File
@@ -1,14 +1,9 @@
'use client';
import { topMovies } from '@/api';
import popularQuery from '@/api/queries/popular';
import useInfiniteList from '@/hooks/useInfiniteList';
const useStarring = ({ actorId }: { actorId?: string }) =>
useInfiniteList({
suspense: true,
queryKey: ['starring', actorId],
enabled: Boolean(actorId),
queryFn: ({ page }) => topMovies({ page, starring: actorId })
});
useInfiniteList(popularQuery({ sortBy: 'vote_average.desc', starring: actorId }));
export default useStarring;
+2 -6
View File
@@ -1,7 +1,7 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { topMovies } from '@/api';
import popularQuery from '@/api/queries/popular';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -15,11 +15,7 @@ export const metadata: Metadata = {
const Top = () => {
const queryClient = getQueryClient();
queryClient.prefetchInfiniteQuery({
queryKey: ['top'],
queryFn: () => topMovies(),
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(popularQuery({ sortBy: 'vote_average.desc' }));
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+2 -2
View File
@@ -1,8 +1,8 @@
'use client';
import { topMovies } from '@/api';
import popularQuery from '@/api/queries/popular';
import useInfiniteList from '@/hooks/useInfiniteList';
const useTop = () => useInfiniteList({ suspense: true, queryKey: ['top'], queryFn: topMovies });
const useTop = () => useInfiniteList(popularQuery({ sortBy: 'vote_average.desc' }));
export default useTop;
-2
View File
@@ -1,5 +1,3 @@
'use client';
import UsersList from '@/components/UsersLists';
const Container = () => <UsersList list='watchlist' label='watch' />;
+4 -7
View File
@@ -1,7 +1,8 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { usersShows } from '@/api';
import { session } from '@/api';
import usersShowsQuery from '@/api/queries/usersShows';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
@@ -12,17 +13,13 @@ export const metadata: Metadata = {
'View your favorite shows on Movie Advisor. Keep track of films you’ve added and revisit your top picks anytime.'
};
const WatchList = async () => {
const WatchList = () => {
const queryClient = getQueryClient();
const list = 'watchlist';
const showType = 'movie';
await queryClient.prefetchInfiniteQuery({
queryKey: [`users-${list}`, showType],
queryFn: () => usersShows({ showType, list, page: '1' }),
initialPageParam: '1'
});
queryClient.prefetchInfiniteQuery(usersShowsQuery({ showType, list, session: session() }));
return (
<HydrationBoundary state={dehydrate(queryClient)}>
+28
View File
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
type TMDBParams = {
params: {
path: string[];
};
};
export async function GET({ nextUrl: { searchParams } }: NextRequest, { params: { path } }: TMDBParams) {
try {
const response = await fetch(`https://api.themoviedb.org/3/${path.join('/')}?${searchParams.toString()}`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`
}
});
if (!response.ok) {
return NextResponse.json({ error: 'Failed to fetch data from TMDb' }, { status: response.status });
}
const data = await response.json();
return NextResponse.json(data);
} catch (error) {
return NextResponse.json({ error: 'An error occurred' }, { status: 500 });
}
}
@@ -1,22 +1,18 @@
import { useRef } from 'react';
import { search } from '@/api';
import searchQuery, { SearchQueryProps } from '@/api/queries/search';
import useInfiniteList from '@/hooks/useInfiniteList';
const useSearch = ({ query, type }: { query: string; type: Show['type'] }) => {
const useSearch = (props: SearchQueryProps) => {
const previousRef = useRef<Show[]>([]);
const infiniteQuery = useInfiniteList({
queryKey: ['search', query, type],
queryFn: ({ page }) => search({ query, page, type }),
enabled: Boolean(query)
});
const infiniteQuery = useInfiniteList(searchQuery(props));
if (infiniteQuery.isFetched) {
previousRef.current = infiniteQuery.shows;
}
if (!query) {
if (!props.query) {
previousRef.current = [];
}
@@ -1,20 +1,9 @@
import { useQuery } from '@tanstack/react-query';
import { credits } from '@/api';
import creditsQuery, { CreditsQueryProps } from '@/api/queries/credits';
interface Props {
showId?: Show['id'];
showType?: Show['type'];
}
export const KEY = ({ showId, showType }: Props) => ['credits', showId, showType];
const useCredits = ({ showId, showType }: Props) => {
return useQuery({
queryKey: KEY({ showId, showType }),
queryFn: () => credits({ showId, showType }),
enabled: Boolean(showId)
});
const useCredits = ({ showId, showType }: CreditsQueryProps) => {
return useQuery(creditsQuery({ showId, showType }));
};
export default useCredits;
+2 -9
View File
@@ -1,19 +1,12 @@
import { useQuery } from '@tanstack/react-query';
import { details } from '@/api';
import detailsQuery from '@/api/queries/details';
interface Props {
showId?: Show['id'];
showType?: Show['type'];
}
export const KEY = ({ showId, showType = 'movie' }: Props) => ['details', showId, showType];
const useDetails = ({ showId, showType = 'movie' }: Props) =>
useQuery({
enabled: Boolean(showId && showType),
queryKey: KEY({ showId, showType }),
queryFn: () => details({ showId: showId!, showType })
});
const useDetails = ({ showId, showType = 'movie' }: Props) => useQuery(detailsQuery({ showId, showType }));
export default useDetails;
+2 -6
View File
@@ -3,7 +3,7 @@
import { startTransition, useCallback } from 'react';
import { atom, getDefaultStore, useAtom } from 'jotai';
import { randomMovies } from '@/api';
import randomQuery from '@/api/queries/random';
import useInfiniteList from '@/hooks/useInfiniteList';
const indexAtom = atom(0);
@@ -13,11 +13,7 @@ export const useSilentIndex = () => getDefaultStore().get(indexAtom);
const useRandomMovie = () => {
const [index, setIndex] = useAtom(indexAtom);
const { shows: movies, fetchNextPage } = useInfiniteList({
suspense: true,
queryKey: ['random-movie'],
queryFn: randomMovies
});
const { shows: movies, fetchNextPage } = useInfiniteList(randomQuery());
if (movies.length && !movies[index]) {
setIndex(0);
@@ -1,3 +1,5 @@
'use client';
import { FC } from 'react';
import Poster from '@/components/Poster';
+2 -8
View File
@@ -1,13 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { popularByType, trendingMovies } from '@/api';
import trendingQuery, { TrendingQueryProps } from '@/api/queries/trending';
const useTrending = ({ type, enabled }: { enabled?: boolean; type: 'trending' | 'streaming' | 'theater' | 'rent' }) => {
return useQuery({
enabled,
queryKey: ['trending', type],
queryFn: () => (type === 'trending' ? trendingMovies() : popularByType({ type }))
});
};
const useTrending = ({ type }: TrendingQueryProps) => useQuery(trendingQuery({ type }));
export default useTrending;
+6 -12
View File
@@ -1,25 +1,19 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { account } from '@/api';
import { useSession } from '@/hooks/useSession';
const KEY = ['account'];
import accountQuery from '@/api/queries/account';
const useAccount = () => {
const queryClient = useQueryClient();
const session = useSession();
const query = useQuery({
enabled: Boolean(session),
staleTime: Infinity,
notifyOnChangeProps: ['data'],
queryKey: KEY,
queryFn: () => account()
});
const options = accountQuery({ session });
const query = useQuery(options);
if (session === null) {
queryClient.removeQueries({ queryKey: KEY });
queryClient.resetQueries({ queryKey: KEY });
queryClient.removeQueries({ queryKey: options.queryKey });
queryClient.resetQueries({ queryKey: options.queryKey });
}
return session ? query.data : undefined;
+2 -2
View File
@@ -5,7 +5,7 @@ interface Props {
suspense?: boolean;
queryKey: QueryKey;
enabled?: boolean;
queryFn: ({ page }: { page: string }) => Promise<Pagination<Show>>;
queryFn: ({ pageParam }: { pageParam: string }) => Promise<Pagination<Show>>;
}
const useInfiniteList = ({ queryKey, queryFn, enabled, suspense }: Props) => {
@@ -14,7 +14,7 @@ const useInfiniteList = ({ queryKey, queryFn, enabled, suspense }: Props) => {
)({
enabled,
queryKey,
queryFn: ({ pageParam }) => queryFn({ page: pageParam }),
queryFn: ({ pageParam }) => queryFn({ pageParam }),
getNextPageParam(pagination) {
if (!pagination || pagination.page === pagination.total) return undefined;
+2 -2
View File
@@ -4,7 +4,7 @@ import { accountStates, updateAccountStates } from '@/api';
import { useFavorites, useFavoritesStateToggle, useWatchList, useWatchListStateToggle } from './useLocalUsersLists';
import { useSession } from './useSession';
import { KEY as USERS_SHOWS_KEY } from './useUsersShows';
import { KEY as USERS_SHOWS_KEY } from '@/api/queries/usersShows';
const KEY = ['show-state'];
@@ -50,7 +50,7 @@ export const useMutateShowState = (show: Show) => {
queryClient.setQueryData<ShowState>(key, snapshot);
},
onSuccess(_, { list, showType }) {
queryClient.invalidateQueries({ queryKey: USERS_SHOWS_KEY({ list, showType }), refetchType: 'all' });
queryClient.invalidateQueries({ queryKey: USERS_SHOWS_KEY({ list, showType, session }), refetchType: 'all' });
}
});
+2 -11
View File
@@ -1,15 +1,9 @@
'use client';
import { usersShows } from '@/api';
import useInfiniteList from './useInfiniteList';
import { useFavorites, useWatchList } from './useLocalUsersLists';
import { useSession } from './useSession';
export const KEY = ({ list, showType }: { showType: Show['type']; list: 'favorite' | 'watchlist' }) => [
`users-${list}`,
showType
];
import usersShowsQuery from '@/api/queries/usersShows';
const useUsersShows = ({ showType, list = 'favorite' }: { showType: Show['type']; list: 'favorite' | 'watchlist' }) => {
const session = useSession();
@@ -17,10 +11,7 @@ const useUsersShows = ({ showType, list = 'favorite' }: { showType: Show['type']
const { shows: favorite } = useFavorites();
const { shows: watchlist } = useWatchList();
const query = useInfiniteList({
queryKey: KEY({ list, showType }),
queryFn: ({ page }) => usersShows({ showType, list, page })
});
const query = useInfiniteList(usersShowsQuery({ showType, list, session }));
return session
? query
+1 -1
View File
@@ -1 +1 @@
if(!self.define){let e,s={};const n=(n,i)=>(n=new URL(n+".js",i).href,s[n]||new Promise((s=>{if("document"in self){const e=document.createElement("script");e.src=n,e.onload=s,document.head.appendChild(e)}else e=n,importScripts(n),s()})).then((()=>{let e=s[n];if(!e)throw new Error(`Module ${n} didn’t register its module`);return e})));self.define=(i,t)=>{const a=e||("document"in self?document.currentScript.src:"")||location.href;if(s[a])return;let c={};const r=e=>n(e,a),o={module:{uri:a},exports:c,require:r};s[a]=Promise.all(i.map((e=>o[e]||r(e)))).then((e=>(t(...e),c)))}}define(["./workbox-4754cb34"],(function(e){"use strict";importScripts(),self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"/_next/app-build-manifest.json",revision:"9ca4cf4934614ee2884f54c0a4ae74f9"},{url:"/_next/static/chunks/106-e4df334a8b6054b2.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/152.e619d8b05424829e.js",revision:"e619d8b05424829e"},{url:"/_next/static/chunks/23-e95fe3862375276d.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/26.286553a5ff2812fc.js",revision:"286553a5ff2812fc"},{url:"/_next/static/chunks/276.c3c1130f2adade69.js",revision:"c3c1130f2adade69"},{url:"/_next/static/chunks/311-d98f807f8da8ea75.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/344.05938a041227e582.js",revision:"05938a041227e582"},{url:"/_next/static/chunks/37-f6e2aef0dac1a9f4.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/383.78d47f7582340f53.js",revision:"78d47f7582340f53"},{url:"/_next/static/chunks/460.ac20021c7496f1d6.js",revision:"ac20021c7496f1d6"},{url:"/_next/static/chunks/497.a16beaad36f500fe.js",revision:"a16beaad36f500fe"},{url:"/_next/static/chunks/61.e269d4a699fba0b6.js",revision:"e269d4a699fba0b6"},{url:"/_next/static/chunks/621-fa4d2ff1cf645813.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/673.362c29137dd3e968.js",revision:"362c29137dd3e968"},{url:"/_next/static/chunks/695.156d21364de6e419.js",revision:"156d21364de6e419"},{url:"/_next/static/chunks/755.5cd959eac5682527.js",revision:"5cd959eac5682527"},{url:"/_next/static/chunks/792.b51012549074b93f.js",revision:"b51012549074b93f"},{url:"/_next/static/chunks/810.6105e84414768b0d.js",revision:"6105e84414768b0d"},{url:"/_next/static/chunks/922.9ce4bf0553cfb724.js",revision:"9ce4bf0553cfb724"},{url:"/_next/static/chunks/957-9f7dee59febd35c3.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/favorites/page-2ad2720a689c7bf7.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/loading-96645736797edde7.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/page-550186c61d98ee57.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/popular/page-0c29524eddadf350.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/similar/page-1126cc975a9ba802.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/starring/page-0fbb653750c18be1.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/top/page-75f0b7e736133ad6.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/(site)/watch-list/page-38ccba9f9dff3e6c.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/_not-found/page-aa0c8e90320336c2.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/app/layout-74481e5fe3b4935f.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/c8bcbd21.63daf74955ffea8b.js",revision:"63daf74955ffea8b"},{url:"/_next/static/chunks/fd9d1056-bdf7d185613ab264.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/framework-f66176bb897dc684.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/main-65cc2be174f92f9a.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/main-app-51cdaff1a81e6b49.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/pages/_app-6a626577ffa902a4.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/pages/_error-1be831200e60c5c0.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/chunks/polyfills-42372ed130431b0a.js",revision:"846118c33b2c0e922d7b3a7676f81f6f"},{url:"/_next/static/chunks/webpack-522f7df141f474e5.js",revision:"vcsU5PL_nCIbZtw1TiXgA"},{url:"/_next/static/css/0d5f6452b2682b9b.css",revision:"0d5f6452b2682b9b"},{url:"/_next/static/css/af880b2e4df9cb52.css",revision:"af880b2e4df9cb52"},{url:"/_next/static/media/46c21389e888bf13-s.woff2",revision:"272930c09ba14c81bb294be1fe18b049"},{url:"/_next/static/media/8888a3826f4a3af4-s.p.woff2",revision:"792477d09826b11d1e5a611162c9797a"},{url:"/_next/static/media/eafabf029ad39a43-s.p.woff2",revision:"43751174b6b810eb169101a20d8c26f8"},{url:"/_next/static/media/f5767adec246cdc1-s.woff2",revision:"7a1c6501aa2b3327c1cf556362a851cb"},{url:"/_next/static/vcsU5PL_nCIbZtw1TiXgA/_buildManifest.js",revision:"2ec694eb52ae4f523f265a46bae4d768"},{url:"/_next/static/vcsU5PL_nCIbZtw1TiXgA/_ssgManifestLine truncated
if(!self.define){let e,s={};const n=(n,a)=>(n=new URL(n+".js",a).href,s[n]||new Promise((s=>{if("document"in self){const e=document.createElement("script");e.src=n,e.onload=s,document.head.appendChild(e)}else e=n,importScripts(n),s()})).then((()=>{let e=s[n];if(!e)throw new Error(`Module ${n} didn’t register its module`);return e})));self.define=(a,i)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(s[t])return;let c={};const d=e=>n(e,t),r={module:{uri:t},exports:c,require:d};s[t]=Promise.all(a.map((e=>r[e]||d(e)))).then((e=>(i(...e),c)))}}define(["./workbox-4754cb34"],(function(e){"use strict";importScripts(),self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"/_next/app-build-manifest.json",revision:"dcb899daa80bc934a3ecade6253ee1ed"},{url:"/_next/static/Gudd5VBBSvZZ12qeh1ETn/_buildManifest.js",revision:"2ec694eb52ae4f523f265a46bae4d768"},{url:"/_next/static/Gudd5VBBSvZZ12qeh1ETn/_ssgManifest.js",revision:"b6652df95db52feb4daf4eca35380933"},{url:"/_next/static/chunks/106-e4df334a8b6054b2.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/141-78e4a62a9eb9ec3f.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/152.e619d8b05424829e.js",revision:"e619d8b05424829e"},{url:"/_next/static/chunks/23-e95fe3862375276d.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/26.286553a5ff2812fc.js",revision:"286553a5ff2812fc"},{url:"/_next/static/chunks/276.c3c1130f2adade69.js",revision:"c3c1130f2adade69"},{url:"/_next/static/chunks/344.05938a041227e582.js",revision:"05938a041227e582"},{url:"/_next/static/chunks/37-f6e2aef0dac1a9f4.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/383.78d47f7582340f53.js",revision:"78d47f7582340f53"},{url:"/_next/static/chunks/460.ac20021c7496f1d6.js",revision:"ac20021c7496f1d6"},{url:"/_next/static/chunks/497.a16beaad36f500fe.js",revision:"a16beaad36f500fe"},{url:"/_next/static/chunks/61.e269d4a699fba0b6.js",revision:"e269d4a699fba0b6"},{url:"/_next/static/chunks/621-fa4d2ff1cf645813.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/673.362c29137dd3e968.js",revision:"362c29137dd3e968"},{url:"/_next/static/chunks/695.156d21364de6e419.js",revision:"156d21364de6e419"},{url:"/_next/static/chunks/755.5cd959eac5682527.js",revision:"5cd959eac5682527"},{url:"/_next/static/chunks/792.b51012549074b93f.js",revision:"b51012549074b93f"},{url:"/_next/static/chunks/810.6105e84414768b0d.js",revision:"6105e84414768b0d"},{url:"/_next/static/chunks/922.9ce4bf0553cfb724.js",revision:"9ce4bf0553cfb724"},{url:"/_next/static/chunks/957-cf3bd689bca85766.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/favorites/page-d86c7d4a1199f6f8.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/loading-96645736797edde7.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/page-b499ead7e2cdc81d.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/popular/page-93e45ee4639153d3.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/similar/page-ac3a3684c680a706.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/starring/page-094a3d3ffd1a9d9a.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/top/page-4f8983666984d5a3.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/(site)/watch-list/page-435498eb058fe335.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/_not-found/page-aa0c8e90320336c2.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/app/layout-173f4f7aa920ea6a.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/c8bcbd21.63daf74955ffea8b.js",revision:"63daf74955ffea8b"},{url:"/_next/static/chunks/fd9d1056-bdf7d185613ab264.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/framework-f66176bb897dc684.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/main-96338ebd2bd5e4cc.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/main-app-51cdaff1a81e6b49.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/pages/_app-6a626577ffa902a4.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/pages/_error-1be831200e60c5c0.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/chunks/polyfills-42372ed130431b0a.js",revision:"846118c33b2c0e922d7b3a7676f81f6f"},{url:"/_next/static/chunks/webpack-30179fe338029346.js",revision:"Gudd5VBBSvZZ12qeh1ETn"},{url:"/_next/static/css/0d5f6452b2682b9b.css",revision:"0d5f6452b2682b9b"},{url:"/_next/static/css/af880b2e4df9cb52.css",revision:"af880b2e4df9cb52"},{url:"/_next/static/media/46c21389e888bf13-s.woff2",revision:"272930c09ba14c81bb294be1fe18b049"},{url:"/_next/static/media/8888a3826f4a3af4-s.p.woff2",revision:"792477d09826b11d1e5a611162c9797a"},{url:"/_next/static/media/eafabf029ad39a43-s.p.woff2",revision:"43751174b6b810eb169101a20d8c26f8"},{url:"/_next/static/media/f5767adec246cdc1-s.woLine truncated