@@ -22,6 +22,10 @@ export type CoreServiceConfig = {
22
22
serviceApiKey : string ;
23
23
serviceAction ?: string ;
24
24
useWalletAuth ?: boolean ;
25
+ /**
26
+ * The number of times to retry the auth request. Default = 3.
27
+ */
28
+ retryCount ?: number ;
25
29
} ;
26
30
27
31
export type TeamAndProjectResponse = {
@@ -179,23 +183,46 @@ export async function fetchTeamAndProject(
179
183
if ( teamId ) {
180
184
url . searchParams . set ( "teamId" , teamId ) ;
181
185
}
182
- const response = await fetch ( url , {
183
- method : "GET" ,
184
- headers : {
185
- ...( authData . secretKey ? { "x-secret-key" : authData . secretKey } : { } ) ,
186
- ...( authData . jwt ? { Authorization : `Bearer ${ authData . jwt } ` } : { } ) ,
187
- "x-service-api-key" : serviceApiKey ,
188
- "content-type" : "application/json" ,
189
- } ,
190
- } ) ;
191
-
192
- let text = "" ;
193
- try {
194
- text = await response . text ( ) ;
195
- return JSON . parse ( text ) ;
196
- } catch {
197
- throw new Error (
198
- `Error fetching key metadata from API: ${ response . status } - ${ text } ` ,
199
- ) ;
186
+
187
+ const retryCount = config . retryCount ?? 3 ;
188
+ let error : unknown | undefined ;
189
+ for ( let i = 0 ; i < retryCount ; i ++ ) {
190
+ try {
191
+ const response = await fetch ( url , {
192
+ method : "GET" ,
193
+ headers : {
194
+ ...( authData . secretKey ? { "x-secret-key" : authData . secretKey } : { } ) ,
195
+ ...( authData . jwt ? { Authorization : `Bearer ${ authData . jwt } ` } : { } ) ,
196
+ "x-service-api-key" : serviceApiKey ,
197
+ "content-type" : "application/json" ,
198
+ } ,
199
+ } ) ;
200
+
201
+ let text = "" ;
202
+ try {
203
+ text = await response . text ( ) ;
204
+ return JSON . parse ( text ) ;
205
+ } catch {
206
+ throw new Error (
207
+ `Error fetching key metadata from API: ${ response . status } - ${ text } ` ,
208
+ ) ;
209
+ }
210
+ } catch ( err : unknown ) {
211
+ error = err ;
212
+ if ( i < retryCount - 1 ) {
213
+ // Add a single retry with a delay between 20ms and 400ms.
214
+ await sleepRandomMs ( 20 , 400 ) ;
215
+ }
216
+ }
200
217
}
218
+ throw error ;
219
+ }
220
+
221
+ /**
222
+ * Sleeps for a random amount of time between min and max, in milliseconds.
223
+ */
224
+ function sleepRandomMs ( min : number , max : number ) {
225
+ return new Promise ( ( resolve ) =>
226
+ setTimeout ( resolve , Math . random ( ) * ( max - min ) + min ) ,
227
+ ) ;
201
228
}
0 commit comments