You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

61 lines
2.1 KiB

import axios from 'axios';
import { toast } from 'react-toastify';
const baseURL = 'http://localhost:4040/api/v1'; //"https://chatstory.ir/api/v1";
const token = '';
const loginURL = 'user/otp/login';
const logoutURL = 'user/logout';
const Axios = axios.create({
withCredentials: true,
validateStatus: null,
baseURL,
});
class dispatch {}
class Proxy {
get = (url, params, opt = {}) => this.check(url, () => Axios.get(url, { params, ...opt }));
post = (url, params, opt = {}) => this.check(url, () => Axios.post(url, params, opt));
put = (url, params, opt = {}) => this.check(url, () => Axios.put(url, params, opt));
delete = (url, params, opt = {}) => this.check(url, () => Axios.delete(url, params, opt));
result = (url, data) => ({
...data,
dispatch: (dispatch) => {
dispatch({ type: url, data });
return data;
},
});
check = async (url, fetch) => {
let response = await fetch();
switch (response.status) {
case 200:
return this.result(url, response.data.data);
case 401:
if (await this.refresh()) return this.result(url, (await fetch()).data.data);
break;
default:
toast(response.data.message);
}
return false;
};
refresh = async () => {
let refresh = localStorage.getItem('refresh');
if (!refresh) window.location.href = '/';
let login = await this.login({}, { headers: { Authorization: `Bearer ${refresh}` } });
return login ? true : false;
};
login = async (data, opt = { headers: { Authorization: `Bearer ${token}` } }) => {
const login = await this.post(loginURL, data, opt);
if (!login || !login.refreshToken) this.result('login', false);
localStorage.setItem('refresh', login.refreshToken);
delete login.refreshToken;
if (data != {}) setTimeout(() => (window.location.href = '/'), 100);
return this.result('login', login);
};
logout = async () => {
this.post(logoutURL);
localStorage.removeItem('refresh');
window.location.href = '/';
};
status = () => (localStorage.getItem('refresh') ? true : false);
}
const _proxy = new Proxy();
export default _proxy;