generated from homebridge/homebridge-plugin-camera-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add retry logic for failed API requests
- Loading branch information
Showing
2 changed files
with
63 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
interface Config { | ||
retries: number; | ||
onRetry: (error: unknown, retries: number) => void; | ||
onFail: (error: unknown) => void; | ||
} | ||
|
||
const retry = async (fn: () => Promise<unknown>, config: Config) => { | ||
const { | ||
retries = 3, | ||
onRetry, | ||
onFail, | ||
} = config; | ||
|
||
try { | ||
return await fn(); | ||
} catch (error) { | ||
if (retries === 0) { | ||
return onFail(error); | ||
} | ||
|
||
onRetry(error, retries); | ||
|
||
return retry(fn, { | ||
...config, | ||
retries: retries - 1, | ||
}); | ||
} | ||
}; | ||
|
||
export default retry; |