Last active
September 12, 2022 17:39
-
-
Save YaronMiro/8daf3fe99909f9448152158b89767b6d to your computer and use it in GitHub Desktop.
Fetch API Wrapper
This file contains hidden or 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
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