-
-
Save stefanorg/11a188bcb71f45a095cf417124746446 to your computer and use it in GitHub Desktop.
Api service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const makeCancelable = promise => { | |
let hasCanceled = false; | |
const wrappedPromise = new Promise((resolve, reject) => { | |
promise.then( | |
val => (hasCanceled ? reject(Error('Request canceled')) : resolve(val)), | |
error => | |
hasCanceled ? reject(Error('Request canceled')) : reject(error), | |
); | |
}); | |
return { | |
promise: wrappedPromise, | |
cancel() { | |
hasCanceled = true; | |
}, | |
}; | |
}; | |
class Api { | |
static buildOptions = (method, auth) => ({ | |
method, | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
dataType: 'json', | |
}, | |
...(auth && Api.token && { Authorization: `Bearer ${Api.token}` }), | |
}); | |
static token = null; | |
static setToken(t) { | |
Api.token = t; | |
} | |
static get(route, params, auth = true) { | |
return this.call(route, params, 'GET', auth); | |
} | |
static put(route, params) { | |
return this.call(route, params, 'PUT'); | |
} | |
static patch(route, params, auth = true) { | |
return this.call(route, params, 'PATCH', auth); | |
} | |
static post(route, params, auth = true) { | |
return this.call(route, params, 'POST', auth); | |
} | |
static delete(route, auth = true) { | |
return this.call(route, null, 'DELETE', auth); | |
} | |
static call(route, params, method, auth) { | |
const host = 'http://baseurl.it/'; | |
let url = host + route; | |
const options = Api.buildOptions(method, auth); | |
if (params) { | |
if (method === 'GET') { | |
url += '?'; | |
Object.keys(params).forEach(key => (url += `${key}=${params[key]}&`)); | |
} else { | |
options.params = { body: JSON.stringify(params) }; | |
} | |
} | |
const currentFetch = fetch(url, options) | |
.then(resp => { | |
const json = resp.json(); | |
if (resp.ok) { | |
return json; | |
} | |
return json.then(err => { | |
console.log(err); | |
throw err; | |
}); | |
}) | |
.catch(err => { | |
console.log(err); | |
}); | |
return makeCancelable(currentFetch); | |
} | |
} | |
export default Api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment