Vitalik
3 weeks ago
3 changed files with 48 additions and 0 deletions
@ -0,0 +1,39 @@
@@ -0,0 +1,39 @@
|
||||
import { authApi } from "@/api"; |
||||
import { authService } from "./auth.service"; |
||||
|
||||
class RefreshSessionService { |
||||
protected refreshTokenPromise?: Promise<any>; |
||||
|
||||
public async refresh(refreshToken?: string) { |
||||
if (this.refreshTokenPromise) { |
||||
return this.refreshTokenPromise; |
||||
} |
||||
|
||||
this.refreshTokenPromise = this.refreshBody(refreshToken); |
||||
|
||||
return this.refreshTokenPromise; |
||||
} |
||||
|
||||
private async refreshBody(refreshToken?: string, attempt = 1) { |
||||
let token = refreshToken; |
||||
if (!token) { |
||||
const existTokens = await authService._getTokensFromStorage(); |
||||
token = existTokens?.refreshToken; |
||||
} |
||||
|
||||
if (!token) return; |
||||
|
||||
try { |
||||
const { data } = await authApi.sendRefreshToken({ |
||||
refreshToken: token, |
||||
}); |
||||
await authService._saveTokens(data); |
||||
} catch (e) { |
||||
console.log(e); |
||||
} finally { |
||||
this.refreshTokenPromise = null; |
||||
} |
||||
} |
||||
} |
||||
|
||||
export const refreshSessionService = new RefreshSessionService(); |
Loading…
Reference in new issue