Skip to content

Commit 1d2ff68

Browse files
committed
fix: ensure byScopeCache is built on initial load
1 parent fdbfe53 commit 1d2ff68

File tree

1 file changed

+34
-25
lines changed

1 file changed

+34
-25
lines changed

src/core/authorization/TokenManager.ts

+34-25
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,39 @@ export class TokenManager {
7777
* This will ensure `this.#storage` is always the latest version.
7878
*/
7979
this.#migrate();
80+
/**
81+
* Build the initial cache of tokens by scope.
82+
*/
83+
this.#buildByScopeCache();
84+
}
85+
86+
#buildByScopeCache() {
87+
const { tokens } = this.#storage.state;
88+
this.#byScopeCache = Object.values(tokens).reduce((acc: ByScopeCache, token) => {
89+
token.scope.split(' ').forEach((scope) => {
90+
/**
91+
* If there isn't an existing token for the scope, add it to the cache.
92+
*/
93+
if (!acc[scope]) {
94+
acc[scope] = token.access_token;
95+
return;
96+
}
97+
/**
98+
* If there is an existing token for the scope, compare the expiration times and keep the token that expires later.
99+
*/
100+
const existing = tokens[acc[scope]];
101+
/**
102+
* If the existing token or the new token is missing the expiration metadata, skip the comparison.
103+
*/
104+
if (!existing.__metadata?.expires || !token.__metadata?.expires) {
105+
return;
106+
}
107+
if (existing.__metadata.expires < token.__metadata.expires) {
108+
acc[scope] = token.access_token;
109+
}
110+
});
111+
return acc;
112+
}, {});
80113
}
81114

82115
/**
@@ -105,31 +138,7 @@ export class TokenManager {
105138
/**
106139
* When the storage is update, we need to rebuild the cache of tokens by scope.
107140
*/
108-
this.#byScopeCache = Object.values(value.state.tokens).reduce((acc: ByScopeCache, token) => {
109-
token.scope.split(' ').forEach((scope) => {
110-
/**
111-
* If there isn't an existing token for the scope, add it to the cache.
112-
*/
113-
if (!acc[scope]) {
114-
acc[scope] = token.access_token;
115-
return;
116-
}
117-
/**
118-
* If there is an existing token for the scope, compare the expiration times and keep the token that expires later.
119-
*/
120-
const existing = value.state.tokens[acc[scope]];
121-
/**
122-
* If the existing token or the new token is missing the expiration metadata, skip the comparison.
123-
*/
124-
if (!existing.__metadata?.expires || !token.__metadata?.expires) {
125-
return;
126-
}
127-
if (existing.__metadata.expires < token.__metadata.expires) {
128-
acc[scope] = token.access_token;
129-
}
130-
});
131-
return acc;
132-
}, {});
141+
this.#buildByScopeCache();
133142
}
134143

135144
/**

0 commit comments

Comments
 (0)