movie-explorer/src/objects/tmdb.tsx

84 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-05-02 20:47:28 +00:00
import axios from 'axios'
import * as auth from '../auth.json';
2024-05-06 09:09:21 +00:00
import { Movie } from './movie-wall';
2024-05-02 20:47:28 +00:00
import { Config } from '../App';
2024-05-06 11:33:00 +00:00
import { makeImgUrl } from '../functions';
2024-05-02 20:47:28 +00:00
const tmdb = axios.create({
baseURL: `https://api.themoviedb.org/3/movie`,
headers: {
Authorization: 'Bearer ' + auth.token,
'Content-Type': 'application/json',
}
})
export default {
2024-05-05 21:59:33 +00:00
/**
* Calls tmdb API/popular and then fires the callback with res.data.results as argument
* @param {Function} callback
* @returns {boolean}
*/
getPopular: async function({ language, region, page }: Config, callback: Function) {
let res = await tmdb.get('/popular',
2024-05-02 20:47:28 +00:00
{
params: {
language,
2024-05-05 21:59:33 +00:00
region,
page
2024-05-02 20:47:28 +00:00
}
})
2024-05-05 21:59:33 +00:00
console.log(res)
if (res.status === 200) {
res = res.data.results
callback(res)
return true
} else {
throw Error("API call failed! Response: " + JSON.stringify(res))
}
},
/**
2024-05-06 09:09:21 +00:00
* Calls TMDB/similar, then fires the callback with res.data.results.unshift(movie) as argument
2024-05-05 21:59:33 +00:00
*/
2024-05-06 09:09:21 +00:00
getSimilar: async function({ language, page }: Config, movie: Movie, callback: Function) {
let res = await tmdb.get(movie.id + '/similar', {
2024-05-05 21:59:33 +00:00
params: {
language,
page
}
})
console.log(res)
if (res.status === 200) {
2024-05-06 09:09:21 +00:00
const array: Array<Movie> = res.data.results
2024-05-07 11:09:48 +00:00
.filter((e: Movie) => {
return e.poster_path
})
array.splice(19)
2024-05-06 09:09:21 +00:00
array.unshift(movie)
callback(array)
2024-05-05 21:59:33 +00:00
return true
} else {
throw Error("API call failed! Response: " + JSON.stringify(res))
}
2024-05-06 11:33:00 +00:00
},
/**
*Calls TMDB/images, and sets the backdrop state accordingly
*
*/
getBackdrop: async function(movie: Movie, setBackdrop: Function) {
let res = await tmdb.get(movie.id + '/images')
console.log(res)
if (res.status === 200) {
const file_path = res.data.backdrops[0].file_path
console.log("file_path:" + file_path)
const imgUrl = makeImgUrl(file_path)
console.log("imgUrl: " + imgUrl)
setBackdrop(imgUrl)
} else {
throw Error("API call failed! Response: " + JSON.stringify(res))
}
2024-05-02 20:47:28 +00:00
}
2024-05-05 21:59:33 +00:00
2024-05-02 20:47:28 +00:00
}