forked from gajus/tmdb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTmdb.js
195 lines (152 loc) · 5.09 KB
/
Tmdb.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// @flow
import xfetch from 'xfetch';
import qs from 'qs';
import deepMapKeys from 'deep-map-keys';
import {
delay
} from 'bluefeather';
import {
camelCase
} from 'lodash';
import Logger from './Logger';
import {
NotFoundError,
RemoteError,
UnexpectedResponseError,
Unimplemented
} from './errors';
import type {
MovieBackdropImageType,
MovieCastCreditType,
MovieCrewCreditType,
MoviePosterImageType,
MovieType,
MovieVideoType,
PersonType
} from './types';
type QueryType = {
[key: string]: string | number | null
};
const log = Logger.child({
namespace: 'Tmdb'
});
class Tmdb {
apiKey: string;
language: string;
constructor (apiKey: string, language: string = 'en') {
this.apiKey = apiKey;
this.language = language;
}
// eslint-disable-next-line flowtype/no-weak-types
async get (resource: string, parameters: QueryType = {}): Object {
// eslint-disable-next-line no-constant-condition
while (true) {
const requestQuery = qs.stringify({
// eslint-disable-next-line id-match
api_key: this.apiKey,
...parameters
});
const response = await xfetch('https://api.themoviedb.org/3/' + resource + '?' + requestQuery, {
isResponseValid: () => {
return true;
},
responseType: 'full'
});
if (!response.headers.has('x-ratelimit-remaining')) {
throw new UnexpectedResponseError();
}
if (!String(response.status).startsWith('2')) {
const rateLimitRemaining = Number(response.headers.get('x-ratelimit-remaining'));
if (!rateLimitRemaining) {
const currentTime = Math.round(new Date().getTime() / 1000);
const rateLimitReset = Number(response.headers.get('x-ratelimit-reset'));
// The minimum 30 seconds cooldown ensures that in case 'x-ratelimit-reset'
// time is wrong, we don't bombard the TMDb server with requests.
const cooldownTime = Math.max(rateLimitReset - currentTime, 30);
log.debug('reached rate limit; waiting %d seconds', cooldownTime);
await delay(cooldownTime * 1000);
// eslint-disable-next-line no-continue
continue;
}
if (response.status === 404) {
throw new NotFoundError();
}
const errorBody = await response.json();
throw new RemoteError(errorBody.status_message, errorBody.status_code);
}
const body = await response.json();
return deepMapKeys(body, camelCase);
}
}
async getMovie (movieId: number): Promise<MovieType> {
const movie = await this.get('movie/' + movieId, {
language: this.language
});
return movie;
}
async getMovieBackdropImages (movieId: number, includeImageLanguage: $ReadOnlyArray<string>): Promise<$ReadOnlyArray<MovieBackdropImageType>> {
const movie = await this.get('movie/' + movieId + '/images', {
include_image_language: includeImageLanguage ? includeImageLanguage.join(',') : null,
language: this.language
});
return movie.backdrops;
}
async getMovieCastCredits (movieId: number): Promise<$ReadOnlyArray<MovieCastCreditType>> {
const movieCredits = await this.get('movie/' + movieId + '/credits', {
language: this.language
});
return movieCredits.cast;
}
async getMovieCrewCredits (movieId: number): Promise<$ReadOnlyArray<MovieCrewCreditType>> {
const movieCredits = await this.get('movie/' + movieId + '/credits', {
language: this.language
});
return movieCredits.crew;
}
async getMoviePosterImages (movieId: number, includeImageLanguage: $ReadOnlyArray<string>): Promise<$ReadOnlyArray<MoviePosterImageType>> {
const movie = await this.get('movie/' + movieId + '/images', {
include_image_language: includeImageLanguage ? includeImageLanguage.join(',') : null,
language: this.language
});
return movie.posters;
}
async getMovieVideos (movieId: number): Promise<$ReadOnlyArray<MovieVideoType>> {
const movie = await this.get('movie/' + movieId + '/videos', {
language: this.language
});
return movie.results;
}
async getPerson (personId: number): Promise<PersonType> {
const person = await this.get('person/' + personId, {
language: this.language
});
return person;
}
async findId (resourceType: 'movie' | 'person', externalSource: 'imdb', externalId: string): Promise<number> {
if (resourceType !== 'movie' && resourceType !== 'person') {
throw new Unimplemented();
}
if (externalSource !== 'imdb') {
throw new Unimplemented();
}
const result = await this.get('find/' + externalId, {
external_source: externalSource + '_id'
});
let results;
if (resourceType === 'movie') {
results = result.movieResults;
} else if (resourceType === 'person') {
results = result.personResults;
} else {
throw new Error('Unexpected state.');
}
if (results.length === 0) {
throw new NotFoundError();
}
if (results.length > 1) {
throw new UnexpectedResponseError();
}
return Number(results[0].id);
}
}
export default Tmdb;