-
-
Save ramiresnas/2cdba9e7a748c7867e357b1db3e62c52 to your computer and use it in GitHub Desktop.
Service
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
| 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