Created
          April 22, 2019 15:44 
        
      - 
      
- 
        Save josuesilva-hotmart/5a323c69de1d0908789edcf33d23e21b to your computer and use it in GitHub Desktop. 
Revisions
- 
        josuesilva-hotmart created this gist Apr 22, 2019 .There are no files selected for viewingThis 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,79 @@ export default class BaseService { defaultHeaders: DefaultHeaders; constructor(token: string) { this.defaultHeaders = { Authorization: `Bearer ${token}`, Accept: "application/json", "Content-Type": "application/json" }; } get(path: string) { return fetch(`${API_URL}${path}`, { headers: this.defaultHeaders }) .then(this.checkUnauthorized) .then(response => { return response.json(); }); } post(path: string, form: Object) { return fetch(`${API_URL}${path}`, this.body(POST_METHOD, form)) .then(this.checkStatus) .then(response => { if ( path.includes("accept") || path.includes("conclude") || path.includes("cancel") || path.includes("signup") ) { return response.text(); } return response.json(); }); } put(path: string, form: Object) { return fetch(`${API_URL}${path}`, this.body(PUT_METHOD, form)) .then(this.checkStatus) .then(response => { return response.json(); }); } del(path: string, form: Object) { return fetch(`${API_URL}${path}`, this.body(DELETE_METHOD, form)) .then(this.checkStatus) .then(response => { return response.json(); }); } body(method: string, form: Object) { return { method, headers: this.defaultHeaders, body: JSON.stringify(form) }; } checkUnauthorized = (response: Object) => { if (response.status === 401) { throw new Error(response.status); } else { return response; } }; checkStatus = (response: Object) => { if (response.status >= 200 && response.status < 300) { return response; } else { console.log(response); let error: Object = new Error(response.status); error.response = response.json(); throw error; } }; }