diff options
author | Fabio Berger <me@fabioberger.com> | 2018-07-14 02:12:37 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-07-14 02:12:37 +0800 |
commit | e2438330f588eba03d50c18943b24d6e7f9e9479 (patch) | |
tree | 33ba5ae3919d67c6a5faa7b0ed07249fa5b8d694 /packages/utils/src/fetchAsync.ts | |
parent | 9b387b8ec3c543b5c96d1887550797a2bb90fe94 (diff) | |
parent | 2f0a9148387b66d75b9ee3856e68f0ed3aa149de (diff) | |
download | dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.tar dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.tar.gz dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.tar.bz2 dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.tar.lz dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.tar.xz dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.tar.zst dexon-sol-tools-e2438330f588eba03d50c18943b24d6e7f9e9479.zip |
Merge pull request #874 from 0xProject/fix/request-timeout-issue
Fix Fetch Timeout Issue
Diffstat (limited to 'packages/utils/src/fetchAsync.ts')
-rw-r--r-- | packages/utils/src/fetchAsync.ts | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/packages/utils/src/fetchAsync.ts b/packages/utils/src/fetchAsync.ts new file mode 100644 index 000000000..c02e5baba --- /dev/null +++ b/packages/utils/src/fetchAsync.ts @@ -0,0 +1,37 @@ +import isNode = require('detect-node'); +import 'isomorphic-fetch'; + +export const fetchAsync = async ( + endpoint: string, + options: RequestInit = {}, + timeoutMs: number = 20000, +): Promise<Response> => { + if (options.signal || (options as any).timeout) { + throw new Error( + 'Cannot call fetchAsync with options.signal or options.timeout. To set a timeout, please use the supplied "timeoutMs" parameter.', + ); + } + let optionsWithAbortParam; + if (!isNode) { + const controller = new AbortController(); + const signal = controller.signal; + setTimeout(() => { + controller.abort(); + }, timeoutMs); + optionsWithAbortParam = { + signal, + ...options, + }; + } else { + // HACK: the `timeout` param only exists in `node-fetch`, and not on the `isomorphic-fetch` + // `RequestInit` type. Since `isomorphic-fetch` conditionally wraps `node-fetch` when the + // execution environment is `Node.js`, we need to cast it to `any` in that scenario. + optionsWithAbortParam = { + timeout: timeoutMs, + ...options, + } as any; + } + + const response = await fetch(endpoint, optionsWithAbortParam); + return response; +}; |