tMDB.ts 2.09 KB
import type { MovieInterface } from "~/interfaces/movie";
import type { TMDBCollectionResponse } from "~/interfaces/response/TMDB";

export function useTMDB() {
  const paramsBase = {
    language: "fr-FR",
  };

  /**
   * Fetch popular movies.
   * @param page
   */
  const fetchPopularMovies = async (page: number) => {
    const { data, status, error, execute } = await useFetch(`/movie/popular`, {
      params: { ...paramsBase, page },
    });
    if (unref(status) === "idle") await execute();
    if (unref(status) === "error" && unref(error)) throw new Error(`Error fetching popular movies: ${error}`);
    return unref(data) as TMDBCollectionResponse;
  };

  /**
   * Search movies
   * @param query
   * @param page
   */
  const searchMovies = async (query: string, page: number) => {
    const { data, status, error, execute } = await useFetch(`/search/movie`, {
      params: { ...paramsBase, page, query: encodeURIComponent(query) },
    });
    if (unref(status) === "idle") await execute();
    if (unref(status) === "error" && unref(error)) throw new Error(`Error searching movies: ${error}`);
    return unref(data) as TMDBCollectionResponse;
  };

  /**
   * Fetch movie details by id.
   * @param id
   */
  const fetchMovieDetails = async (id: number | string) => {
    const { data, status, error, execute } = await useFetch(`/movie/${id}`, {
      params: { ...paramsBase },
    });
    if (unref(status) === "idle") await execute();
    if (unref(status) === "error" && unref(error)) throw new Error(`An error occurred when fetching movie details: ${error}`);
    return unref(data) as MovieInterface;
  };

  /**
   * Fetch movie credits
   */
  const fetchMovieCredits = async (id: number | string) => {
    const { data, status, error, execute } = await useFetch(`/movie/${id}/credits`, {
      params: { ...paramsBase },
    });
    if (unref(status) === "idle") await execute();
    if (unref(status) === "error" && unref(error)) throw new Error(`Error fetching movie credits: ${error}`);
    return unref(data);
  };

  return { fetchPopularMovies, searchMovies, fetchMovieDetails, fetchMovieCredits };
}