Skip to content

Instantly share code, notes, and snippets.

@ramiresnas
Created February 19, 2019 21:59
Show Gist options
  • Select an option

  • Save ramiresnas/2cdba9e7a748c7867e357b1db3e62c52 to your computer and use it in GitHub Desktop.

Select an option

Save ramiresnas/2cdba9e7a748c7867e357b1db3e62c52 to your computer and use it in GitHub Desktop.
Service
export default class Service {
constructor(){
this.host = process.env.API_URL
const headers = new Headers()
const token = sessionStorage.getItem('token')
headers.append('Authorization',`Bearer ${token}`)
this.options = {
headers : headers,
method : 'GET',
mode : 'cors',
body : null
}
}
/**
*
* @param {String} endpoint
* @param {object} body
* @param {boolean} isData
*/
post(endpoint,body,isData){
return new Promise( (resolve,reject) => {
if(isData){
this.options.body = body
}else{
this.options.body = JSON.stringify(body)
}
this.options.method = 'POST'
endpoint = endpoint.startsWith("/") ? endpoint : "/"+endpoint
fetch(this.host+endpoint,this.options)
.then(response => response.json())
.then(response => this.handleResponse(response,resolve))
.catch(error => reject(error))
})
}
get(endpoint){
return new Promise( (resolve, reject)=>{
endpoint = endpoint.startsWith("/") ? endpoint : "/"+endpoint
fetch(this.host+endpoint,this.options)
.then(response => response.json())
.then(response => this.handleResponse(response,resolve))
.catch(error => reject(error))
})
}
put(endpoint,body,isData){
return new Promise( (resolve,reject) => {
if(isData){
this.options.body = body
}else{
this.options.body = JSON.stringify(body)
}
this.options.method = 'PUT'
endpoint = endpoint.startsWith("/") ? endpoint : "/"+endpoint
fetch(this.host+endpoint,this.options)
.then(response => response.json())
.then(response => this.handleResponse(response,resolve))
.catch(error => reject(error))
})
}
/**
* @param {Response} response
* @param {object} resolve
*/
handleResponse(response,resolve){
if(response.success){
resolve(response.data)
}else{
throw new Error(response.httpMessage)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment