front
parent
76af91c37c
commit
ab8c506dd5
32 changed files with 125 additions and 61 deletions
@ -0,0 +1,50 @@ |
||||
import axios from 'axios' |
||||
const Axios = axios.create({ |
||||
withCredentials: true, |
||||
validateStatus:null, |
||||
baseURL: "https://chatstory.ir/api/v1" |
||||
// baseURL: "http://localhost:4040/api/v1"
|
||||
}) |
||||
class Proxy{ |
||||
constructor({alert,loginUrl}={}){ |
||||
this.alert = alert || window.alert; |
||||
this.loginUrl = loginUrl || "user/otp/login"; |
||||
} |
||||
get = (url,params,opt={})=> this.check(()=>Axios.get(url,{params,...opt})); |
||||
post = (url,params,opt={})=> this.check(()=>Axios.post(url,params,opt)); |
||||
put = (url,params,opt={})=> this.check(()=> Axios.put(url,params,opt)); |
||||
delete = (url,params,opt={})=> this.check(()=> Axios.delete(url,params,opt)); |
||||
check = async (fetch)=>{ |
||||
let response = await fetch() |
||||
switch(response.status){ |
||||
case 200: return response.data.data;
|
||||
case 401:
|
||||
console.log("refreshing") |
||||
if(await this.refresh()) return (await fetch()).data.data; |
||||
break; |
||||
default: window.alert(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={})=>{ |
||||
const login = await this.post(this.loginUrl,data,opt) |
||||
if(!login) return false; |
||||
localStorage.setItem("refresh",login.refreshToken) |
||||
delete login.refreshToken |
||||
return login |
||||
} |
||||
logout = async()=>{ |
||||
localStorage.removeItem("refresh"); |
||||
window.location.href = "/" |
||||
} |
||||
status = ()=>localStorage.getItem("refresh")?true:false; |
||||
|
||||
} |
||||
const _proxy = new Proxy() |
||||
export default _proxy; |
Loading…
Reference in new issue