Skip to content

Instantly share code, notes, and snippets.

@YaronMiro
Last active September 12, 2022 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YaronMiro/8daf3fe99909f9448152158b89767b6d to your computer and use it in GitHub Desktop.
Save YaronMiro/8daf3fe99909f9448152158b89767b6d to your computer and use it in GitHub Desktop.
Fetch API Wrapper
class FetchWrapper {
constructor(baseURL) {
this._baseURL = baseURL ;
}
get baseURL (){
return this._baseURL ;
}
handleResponseError(response){
if (!response.ok) {
throw new Error({message: response.statusText})
}
}
handleError(error){
console.log('[ERROR]', error.message)
}
handleResponse(response){
this.handleResponseError(response);
return response.json();
}
generateEndpoint (endpoint) {
return this.baseURL + endpoint;
}
send(endpoint, options ={})
get (endpoint, options ={}) {
const defaultOptions = {};
const mergedOptions = {...defaultOptions, ...options};
return fetch(this.baseURL + endpoint, mergedOptions)
.then(this.handleResponse.bind(this))
.catch(this.handleError)
}
put(endpoint, body, options ={}) {
const defaultOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
};
const mergedOptions = {...defaultOptions, ...options, body: JSON.stringify(body)};
return fetch(this.generateEndpoint(endpoint), mergedOptions)
.then(this.handleResponse.bind(this))
.catch(this.handleError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment