-
Notifications
You must be signed in to change notification settings - Fork 6
/
Tmdb.js
205 lines (161 loc) · 5.53 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
196
197
198
199
200
201
202
203
204
205
// @flow
import got from 'got';
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,
CompanyType,
} 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 response = await got('https://api.themoviedb.org/3/' + resource, {
responseType: 'json',
searchParams: {
// eslint-disable-next-line id-match
api_key: this.apiKey,
// eslint-disable-next-line no-extra-parens, flowtype/no-weak-types
...(parameters: Object),
},
throwHttpErrors: false,
});
if (!String(response.statusCode).startsWith('2')) {
if (response.headers['x-ratelimit-remaining']) {
const rateLimitRemaining = Number(response.headers['x-ratelimit-remaining']);
if (!rateLimitRemaining) {
const currentTime = Math.round(new Date().getTime() / 1000);
const rateLimitReset = Number(response.headers['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.statusCode === 404) {
throw new NotFoundError();
}
throw new RemoteError(response.body.status_message, response.body.status_code);
}
return deepMapKeys(response.body, camelCase);
}
}
async getMovie (movieId: number): Promise<MovieType> {
const movie = await this.get('movie/' + movieId, {
language: this.language,
});
return {
...movie,
// Revenue can be 0, e.g. https://gist.github.com/gajus/b396a7e1af22977b0d98f4c63a664d44#file-response-json-L94
revenue: movie.revenue || null,
// Runtime can be 0, e.g. https://gist.github.com/gajus/b396a7e1af22977b0d98f4c63a664d44#file-response-json-L95
runtime: movie.runtime || null,
};
}
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 getCompany (companyId: number): Promise<CompanyType> {
const company = await this.get('company/' + companyId, {
language: this.language,
});
return company;
}
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;