1
1
import { refreshAccessToken } from 'apis/auth'
2
+ import { getDefaultStore } from 'jotai'
2
3
import { noop } from 'lodash-es'
3
4
4
- import { AuthState , fromCredentials } from 'store/auth'
5
+ import { authAtom , fromCredentials } from 'store/auth'
5
6
import {
6
7
InvalidTokenError ,
7
8
NetworkError ,
8
9
TokenExpiredError ,
9
10
UnauthorizedError ,
10
11
} from 'utils/error'
11
12
12
- export namespace TokenManager {
13
- let getAuth : ( ) => AuthState = ( ) => ( { } )
14
- let setAuth : ( set : AuthState | ( ( auth : AuthState ) => AuthState ) ) => void =
15
- noop
13
+ let store = getDefaultStore ( )
14
+ let pendingGetToken : Promise < string > | undefined
16
15
17
- export function setAuthGetter ( get : typeof getAuth ) {
18
- getAuth = get
19
- }
20
- export function setAuthSetter ( set : typeof setAuth ) {
21
- setAuth = set
22
- }
23
-
24
- let pendingGetToken : Promise < string > | undefined
25
-
26
- export async function updateAndGetToken ( ) {
16
+ export const TokenManager = {
17
+ setStore ( newStore : typeof store ) {
18
+ store = newStore
19
+ } ,
20
+ updateAndGetToken ( ) {
27
21
if ( pendingGetToken ) {
28
22
return pendingGetToken
29
23
}
30
24
31
25
const { token, validBefore, refreshToken, refreshTokenValidBefore } =
32
- getAuth ( )
26
+ store . get ( authAtom )
33
27
34
28
const endTime = + new Date ( validBefore || 0 ) || 0
35
29
const refreshEndTime = + new Date ( refreshTokenValidBefore || 0 ) || 0
@@ -46,15 +40,15 @@ export namespace TokenManager {
46
40
}
47
41
48
42
if ( ! refreshToken ) {
49
- setAuth ( { } )
43
+ store . set ( authAtom , { } )
50
44
throw new InvalidTokenError ( )
51
45
}
52
46
53
47
if ( refreshEndTime > now ) {
54
48
try {
55
49
const res = await refreshAccessToken ( { refreshToken } )
56
50
57
- setAuth ( fromCredentials ( res ) )
51
+ store . set ( authAtom , fromCredentials ( res ) )
58
52
59
53
return res . token
60
54
} catch ( e ) {
@@ -64,7 +58,7 @@ export namespace TokenManager {
64
58
throw new TokenExpiredError ( )
65
59
}
66
60
} else {
67
- setAuth ( { } )
61
+ store . set ( authAtom , { } )
68
62
throw new InvalidTokenError ( )
69
63
}
70
64
} ) ( )
@@ -78,5 +72,5 @@ export namespace TokenManager {
78
72
. catch ( noop )
79
73
80
74
return pendingGetToken
81
- }
75
+ } ,
82
76
}
0 commit comments