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;