57 lines
2.2 KiB
TypeScript
57 lines
2.2 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);
|
|
|
|
// TMDB search is loose (e.g. "dune" matches the French "Anatomie d'une chute"). Drop results whose
|
|
// title shares no query token, so a zero-overlap match can't ride its rating into the top of the list.
|
|
const normalize = (value: string) =>
|
|
value
|
|
.toLowerCase()
|
|
.normalize('NFD')
|
|
.replace(/[\u0300-\u036f]/g, '');
|
|
const titleKey = (value: string) => normalize(value).replace(/[^a-z0-9]/g, '');
|
|
const queryTokens = (query: string) =>
|
|
normalize(query)
|
|
.split(/[^a-z0-9]+/)
|
|
.filter(Boolean);
|
|
|
|
const matchesTitle = (show: Show, tokens: string[]) => {
|
|
if (!tokens.length) return true;
|
|
const title = titleKey(show.title);
|
|
return tokens.some((token) => title.includes(token));
|
|
};
|
|
|
|
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');
|
|
const tokens = queryTokens(query);
|
|
|
|
return {
|
|
page: Math.max(moviesPage.page, seriesPage.page),
|
|
total: Math.max(moviesPage.total, seriesPage.total),
|
|
results: [...moviesPage.results, ...seriesPage.results]
|
|
.filter((show) => matchesTitle(show, tokens))
|
|
.sort(byRating)
|
|
};
|
|
}),
|
|
enabled: Boolean(query)
|
|
});
|
|
|
|
export default searchQuery;
|