-
Notifications
You must be signed in to change notification settings - Fork 903
Expand file tree
/
Copy pathrefresh-controller.ts
More file actions
41 lines (34 loc) · 1.16 KB
/
refresh-controller.ts
File metadata and controls
41 lines (34 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import type { RefreshableScheme, HTTPResponse } from '../types'
import type { Auth } from '../core'
export class RefreshController {
public $auth: Auth
private _refreshPromise: Promise<HTTPResponse | void> = null
constructor(public scheme: RefreshableScheme) {
this.$auth = scheme.$auth
}
// Multiple requests will be queued until the first has completed token refresh.
handleRefresh(): Promise<HTTPResponse | void> {
// Another request has started refreshing the token, wait for it to complete
if (this._refreshPromise) {
return this._refreshPromise
}
return this._doRefresh()
}
// Returns a promise which is resolved when refresh is completed
// Call this function when you intercept a request with an expired token.
private _doRefresh(): Promise<HTTPResponse | void> {
this._refreshPromise = new Promise((resolve, reject) => {
this.scheme
.refreshTokens()
.then((response) => {
this._refreshPromise = null
resolve(response)
})
.catch((error) => {
this._refreshPromise = null
reject(error)
})
})
return this._refreshPromise
}
}