tMDB.ts
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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 };
}