Skip to content

Instantly share code, notes, and snippets.

@santospatrick
Forked from paulsturgess/service.js
Created May 18, 2019 21:07
Show Gist options
  • Save santospatrick/752a605dca66cbbdba5abf62c6cfcd74 to your computer and use it in GitHub Desktop.
Save santospatrick/752a605dca66cbbdba5abf62c6cfcd74 to your computer and use it in GitHub Desktop.
An example Service class wrapper for Axios
import axios from "axios";
class HttpService {
constructor() {
const token = window.localStorage.getItem("token");
const service = axios.create({
baseURL: process.env.REACT_APP_API_URL,
headers: token
? {
Authorization: `Bearer ${token}`,
}
: {},
});
service.interceptors.response.use(this.handleSuccess, this.handleError);
this.service = service;
}
handleSuccess(response) {
return response;
}
handleError(error) {
switch (error.response.status) {
case 401:
// Token expired
delete this.service.defaults.headers["Authorization"];
window.localStorage.removeItem("token");
this.redirectTo("/login");
break;
case 404:
// Not found
this.redirectTo("/404");
break;
default:
// Internal server error
this.redirectTo("/500");
break;
}
return Promise.reject(error);
}
redirectTo(url) {
window.location.href = url;
}
get(...args) {
return this.service.get(...args);
}
post(...args) {
return this.service.post(...args);
}
put(...args) {
return this.service.put(...args);
}
patch(...args) {
return this.service.patch(...args);
}
delete(...args) {
return this.service.delete(...args);
}
}
export default new HttpService();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment