-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.js
93 lines (78 loc) · 2.82 KB
/
api.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import axios from 'axios';
import * as c from './constants';
export function getData() {
return new Promise((resolve, reject) => {
let requests = [
axios.get(c.POPULAR),
axios.get(c.TOP_RATED),
axios.get(c.NOW_PLAYING),
axios.get(c.UPCOMING)
];
axios.all(requests)
.then(axios.spread((popular, top_rated, now_playing, upcoming) => {
popular = popular.data.results;
top_rated = top_rated.data.results;
now_playing = now_playing.data.results;
upcoming = upcoming.data.results;
let data = {popular, top_rated, now_playing, upcoming};
resolve(data);
}))
.catch(error => reject(handleError(error)));
});
};
export function getMoviesByGenre(genre_id) {
return new Promise((resolve, reject) => {
axios.get(c.DISCOVER + "&with_genres=" + genre_id)
.then(res => res.data)
.then((data) => resolve(data))
.catch(error => reject(handleError(error)));
});
};
export function getMovieDetails(movie_id) {
return new Promise((resolve, reject) => {
let requests = [
axios.get(c.MOVIE_DETAILS + movie_id + c.API_KEY + c.API_PARAMS),
axios.get(c.MOVIE_DETAILS + movie_id + c.CREDITS),
axios.get(c.MOVIE_DETAILS + movie_id + c.SIMILAR)
];
axios.all(requests)
.then(axios.spread((details, credits, similar) => {
details = details.data;
credits = credits.data;
similar = similar.data.results;
let videos = details.videos.results;
let data = {...details, ...credits, similar, videos};
resolve(data);
}))
.catch(error => reject(handleError(error)));
});
};
function handleError(error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
let {data} = error.response;
error = data.error;
}
if (error.hasOwnProperty("message")) error = error.message;
return error;
};
export function searchMovies(keyword) {
return new Promise((resolve, reject) => {
axios.get(c.SEARCH + "&query=" + keyword)
.then(res => res.data)
.then((data) => resolve(data))
.catch((error) => reject(handleError(error)));
});
}
export function getMoviesByType(url, type = null, dispatch) {
return new Promise((resolve, reject) => {
axios.get(url)
.then(res => res.data)
.then((data) => {
if (type) dispatch({type, data});
resolve(data);
})
.catch((error) => reject(handleError(error)));
});
};