Skip to content

Instantly share code, notes, and snippets.

@shoaibmehedi7
Created July 24, 2022 09:22
Show Gist options
  • Save shoaibmehedi7/724eda94bba18b5c2c5226591c9071bf to your computer and use it in GitHub Desktop.
Save shoaibmehedi7/724eda94bba18b5c2c5226591c9071bf to your computer and use it in GitHub Desktop.
import axios from 'axios';
import { getCsrfToken, getSession } from 'next-auth/react';
class Service {
service: any;
constructor() {
const service = axios.create({
headers: {
'Content-Type': 'application/json',
authorization: `Bearer ${getSession().then((session: any) => session.accessToken)}`,
csrf: `${getCsrfToken()}`,
},
});
service.interceptors.response.use(this.handleSuccess, this.handleError);
this.service = service;
}
handleSuccess(response: any) {
return response;
}
handleError = (error: { response: { status: any } }) => {
console.log('server 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: Document, path: string) => {
document.location = path;
};
get(path: any, callback: (arg0: any, arg1: any) => any) {
return this.service
.get(path)
.then((response: { status: any; data: any }) => callback(response.status, response.data));
}
patch(path: any, payload: any, callback: (arg0: any, arg1: any) => any) {
return this.service
.request({
method: 'PATCH',
url: path,
responseType: 'json',
data: payload,
})
.then((response: { status: any; data: any }) => callback(response.status, response.data));
}
post(path: any, payload: any, callback: (arg0: any, arg1: any) => any) {
return this.service
.request({
method: 'POST',
url: path,
responseType: 'json',
data: payload,
})
.then((response: { status: any; data: any }) => callback(response.status, response.data));
}
}
export default new Service();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment