-
-
Notifications
You must be signed in to change notification settings - Fork 260
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
enhancement(PDF): Create fetchWithTimeout util and use in getTransact…
…ionPdf
- Loading branch information
1 parent
b2848ee
commit f1e5b06
Showing
3 changed files
with
54 additions
and
8 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import fetch from 'node-fetch'; | ||
|
||
import logger from './logger'; | ||
|
||
/** | ||
* Make a fetch call with a timeout. Returns a thenable Promise. | ||
* @param {Object} fetchParams The object of options to pass into the fetch request. | ||
* @param {String} fetchParams.url The url to fetch. | ||
* @param {Object} [fetchParams.options] The method, headers, and other options for node-fetch. Default method is GET. | ||
* @param {Number} [timeoutInMs] The callback to call with the authorized client. Default is 5000 ms. | ||
*/ | ||
|
||
export const fetchWithTimeout = (fetchParams, timeoutInMs = 5000) => { | ||
return new Promise((resolve, reject) => { | ||
let timedOut = false; | ||
|
||
const timer = setTimeout(() => { | ||
timedOut = true; | ||
logger.warn(`Fetch request to ${fetchParams.url} timed out`); | ||
return reject(new Error(`Fetch request to ${fetchParams.url} timed out`)); | ||
}, timeoutInMs); | ||
|
||
fetch(fetchParams.url, fetchParams.options) | ||
.then( | ||
response => { | ||
if (!timedOut) { | ||
logger.info(`Fetch request to ${fetchParams.url} successful`); | ||
return resolve(response); | ||
} | ||
}, | ||
err => { | ||
if (timedOut) { | ||
return; | ||
} | ||
return reject(new Error(`Fetch error: ${err.message}`)); | ||
}, | ||
) | ||
.finally(() => { | ||
clearTimeout(timer); | ||
}); | ||
}); | ||
}; |
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