-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathomdb.js
More file actions
48 lines (36 loc) · 1.35 KB
/
omdb.js
File metadata and controls
48 lines (36 loc) · 1.35 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
const omdb = (function() { //module pattern
let exportable = {}; //everything assigned to exportable is publicly exposed outside of omdb
const baseGetUrl = 'http://www.omdbapi.com?i='; //note "i", for movie ids in IMDB format
const apiFragment = '&apikey=';
let apiKey;
let searchTerm;
let imdbId;
/*
PRIVATE METHODS
*/
//create API-specific URLs
const idUrl = (imdbId) => `${baseGetUrl}${imdbId}${apiFragment}${apiKey}`;
//check that HTTP status code was in 200-299 range, else throw error and stop the train
let validate = (response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
//
let validateAndParse = (promise) => {
let results = promise.then(validate) //check HTTP response for any error
.then((response) => response.json()) //get json from promise
.catch((error) => console.error(error)); //catch any promise-related errors
return results;
}
/*
PUBLIC METHODS
*/
exportable.setKey = (newKey) => apiKey = newKey;
exportable.getOneMovieProfile = (imdbId) => {
let promise = fetch(idUrl(imdbId)); //fetch() returns a promise
return validateAndParse(promise);
};
return exportable; //expose all of this object's properties outside of omdb
}())