tMDB.ts 2.25 KB
import type { RuntimeConfig } from "nuxt/schema";

export const useTMDB = function () {
  const runtimeconfig: RuntimeConfig = useRuntimeConfig();
  const apiUrl = runtimeconfig.public.apiTMDBUrl;
  const apiKey = runtimeconfig.public.apiTMDBSecret;

  /**
   * Fetch popular movies.
   * @param page
   */
  const fetchPopularMovies = async (page: number) => {
    try {
      const response = await fetch(`${apiUrl}/movie/popular?api_key=${apiKey}&language=fr-FR&page=${page}`);
      if (!response.ok) {
        console.error("An error occurred when fetching popular movies:");
      } else {
        return await response.json();
      }
    } catch (error) {
      console.error("Error fetching popular movies:", error);
    }
  };

  /**
   * Search movies
   * @param query
   * @param page
   */
  const searchMovies = async (query: string, page: number) => {
    try {
      const response = await fetch(
        `${apiUrl}/search/movie?api_key=${apiKey}&language=fr-FR&query=${encodeURIComponent(query)}&page=${page}`,
      );
      if (!response.ok) {
        console.error("An error occurred when searching movies:");
      } else {
        return await response.json();
      }
    } catch (error) {
      console.error("Error searching movies:", error);
    }
  };

  /**
   * Fetch movie details by id.
   * @param id
   */
  const fetchMovieDetails = async (id: number | string) => {
    try {
      const response = await fetch(`${apiUrl}/movie/${id}?api_key=${apiKey}&language=fr-FR`);
      if (!response.ok) {
        console.error("An error occurred when fetching movie details:");
      } else {
        return await response.json();
      }
    } catch (error) {
      console.error("Error fetching details:", error);
    }
  };

  /**
   * Fetch movie credits
   */
  const fetchMovieCredits = async (id: number | string) => {
    try {
      const response = await fetch(`${apiUrl}/movie/${id}/credits?api_key=${apiKey}&language=fr-FR`);
      if (!response.ok) {
        console.error("An error occurred when fetching movie credits:");
      } else {
        return await response.json();
      }
    } catch (error) {
      console.error("Error fetching movie credits:", error);
    }
  };

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