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'; window.baseURL = baseURL; 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.error(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) return this.result('login', false); localStorage.setItem('refresh', login.refreshToken); delete login.refreshToken; localStorage.setItem('userData', JSON.stringify(login)); if (data != {}) window.router.setState({ islogin: true }); return this.result('login', login); }; logout = async () => { this.post(logoutURL); localStorage.removeItem('refresh'); localStorage.removeItem('userData'); window.router.setState({ islogin: false }); return this.result('logout', {}); }; status = () => { let refresh = localStorage.getItem('refresh'); let userData = localStorage.getItem('userData'); if (!refresh) return false; if (refresh == 'undefined') { localStorage.removeItem('refresh'); localStorage.removeItem('userData'); return false; } return JSON.parse(userData); }; } const _proxy = new Proxy(); export default _proxy;