Files
movie-advisor/data/queries/search.ts
T

35 lines
1.4 KiB
TypeScript

import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show';
export type SearchQueryProps = { query: string };
// Votes-weighted (Bayesian) rating so a 10.0 with a single vote cannot outrank the actual match
const MIN_VOTES = 300;
const MEAN_RATING = 6;
const weightedRating = (show: Show) => (show.votes * show.rating + MIN_VOTES * MEAN_RATING) / (show.votes + MIN_VOTES);
const byRating = (a: Show, b: Show) =>
weightedRating(b) - weightedRating(a) || b.votes - a.votes || a.title.localeCompare(b.title);
const searchQuery = ({ query }: SearchQueryProps) => ({
queryKey: ['search', query],
queryFn: ({ pageParam }: { pageParam: string }) =>
Promise.all([
movieAdvisor.get<TMDBPagination<Movie>>('/search/movie', { params: { page: pageParam, query } }),
movieAdvisor.get<TMDBPagination<Series>>('/search/tv', { params: { page: pageParam, query } })
]).then(([movies, series]) => {
const moviesPage = mapMoviesSeriesResponseToShows(movies, 'movie');
const seriesPage = mapMoviesSeriesResponseToShows(series, 'tv');
return {
page: Math.max(moviesPage.page, seriesPage.page),
total: Math.max(moviesPage.total, seriesPage.total),
results: [...moviesPage.results, ...seriesPage.results].sort(byRating)
};
}),
enabled: Boolean(query)
});
export default searchQuery;