Skip to content

Instantly share code, notes, and snippets.

@paulsturgess
Last active February 2, 2024 17:24
Show Gist options
  • Save paulsturgess/ebfae1d1ac1779f18487d3dee80d1258 to your computer and use it in GitHub Desktop.
Save paulsturgess/ebfae1d1ac1779f18487d3dee80d1258 to your computer and use it in GitHub Desktop.
An example Service class wrapper for Axios
import axios from 'axios';
class Service {
constructor() {
let service = axios.create({
headers: {csrf: 'token'}
});
service.interceptors.response.use(this.handleSuccess, this.handleError);
this.service = service;
}
handleSuccess(response) {
return response;
}
handleError = (error) => {
switch (error.response.status) {
case 401:
this.redirectTo(document, '/')
break;
case 404:
this.redirectTo(document, '/404')
break;
default:
this.redirectTo(document, '/500')
break;
}
return Promise.reject(error)
}
redirectTo = (document, path) => {
document.location = path
}
get(path, callback) {
return this.service.get(path).then(
(response) => callback(response.status, response.data)
);
}
patch(path, payload, callback) {
return this.service.request({
method: 'PATCH',
url: path,
responseType: 'json',
data: payload
}).then((response) => callback(response.status, response.data));
}
post(path, payload, callback) {
return this.service.request({
method: 'POST',
url: path,
responseType: 'json',
data: payload
}).then((response) => callback(response.status, response.data));
}
}
export default new Service;
@ittroller
Copy link

how to handle call api refresh token with this class ? please send me some example

@Ankit9997
Copy link

serviceWrapper

@champion-054
Copy link

Is it possible to provide a parameterized constructor? And how exactly can we implement it?

@Sovai
Copy link

Sovai commented Jan 29, 2022

why do we need this wrapper service instead of direct axios?

@Darshan072
Copy link

@Sovai just to add all the common config at one place.

@deepaksemwal121
Copy link

@Sovai if any time you need to change the axios for XYZ reasons you don't have to do it manually in all of your requests you can change it in a single file. It will save your time and efforts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment