-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch.js
51 lines (38 loc) · 1.29 KB
/
fetch.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
var nygFetch = (function() {
var nygFetch = {}
nygFetch.checkAvailability = function(elementId = undefined) {
if (!self.fetch) {
const errorMessage = 'Your web browser doesn\'t support the Fetch API, please use a newer one.'
if (elementId) {
document.getElementById(elementId).textContent = errorMessage
}
else {
alert(errorMessage)
}
}
}
nygFetch.fetch = function(url) {
return fetch(url)
.then(checkResponseStatus)
.catch(nygFetch.rethrowError)
}
nygFetch.fetchJSON = function(url, external = false) {
const extUrl = 'https://cors-anywhere.herokuapp.com/' + url
return nygFetch
.fetch(external ? extUrl : url)
.then(response => response.json())
.catch(nygFetch.rethrowError)
}
nygFetch.rethrowError = function(error) {
throw error
}
function checkResponseStatus(response) {
if (response.status >= 200 && response.status < 300 || response.status == 0) {
return response
}
else {
throw new Error(`Error: received response with status: [${response.status}, "${response.statusText}"]`)
}
}
return nygFetch
})()