tMDB.ts
2.14 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
63
64
65
66
67
68
69
70
71
import type { RuntimeConfig } from "nuxt/schema";
export function useTMDB() {
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) throw new Error("An error occurred when fetching popular movies");
return await response.json();
}
catch (error) {
throw new 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) throw new Error("An error occurred when searching movies");
return await response.json();
}
catch (error) {
throw new 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) throw new Error("An error occurred when fetching movie details");
return await response.json();
}
catch (error) {
throw new 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) throw new Error("An error occurred when fetching movie credits");
return await response.json();
}
catch (error) {
throw new Error(`Error fetching movie credits: ${error}`);
}
};
return { fetchPopularMovies, searchMovies, fetchMovieDetails, fetchMovieCredits };
}