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; } }; }