-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
try to use safely-retry as local file
- Loading branch information
1 parent
c6b0c67
commit 2a04df9
Showing
3 changed files
with
43 additions
and
2 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
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,42 @@ | ||
/* eslint-disable @typescript-eslint/ban-ts-comment */ | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
function isPromise<T, S>(obj: PromiseLike<T> | S): obj is PromiseLike<T> { | ||
return ( | ||
!!obj && | ||
(typeof obj === 'object' || typeof obj === 'function') && | ||
'then' in obj && | ||
typeof obj.then === 'function' | ||
); | ||
} | ||
|
||
function safelyTry<T, E = Error>( | ||
fn: ((...args: any[]) => T) | (() => T), | ||
...args: any[] | ||
): T extends PromiseLike<any> | ||
? | ||
| Promise<{ data: undefined; error: E }> | ||
| Promise<{ data: Awaited<T>; error: undefined }> | ||
: { data: undefined; error: E } | { data: T; error: undefined } { | ||
try { | ||
// try calling the function | ||
const x = fn(...args); | ||
|
||
// asynchronous functions | ||
if (isPromise(x)) { | ||
// @ts-ignore | ||
return Promise.resolve(x).then( | ||
(value) => ({ data: value as Awaited<T>, error: undefined }), | ||
(error) => ({ data: undefined, error: error as E }), | ||
); | ||
} | ||
|
||
// synchronous functions | ||
// @ts-ignore | ||
return { data: x, error: undefined }; | ||
} catch (error) { | ||
// @ts-ignore | ||
return { data: undefined, error: error as E }; | ||
} | ||
} | ||
|
||
export default safelyTry; |