Skip to content

Instantly share code, notes, and snippets.

@jordan112
Last active April 9, 2020 15:22
Show Gist options
  • Save jordan112/51d52e5622f7ad0854ba95da3b4cc19b to your computer and use it in GitHub Desktop.
Save jordan112/51d52e5622f7ad0854ba95da3b4cc19b to your computer and use it in GitHub Desktop.
import fetch from 'node-fetch';
const https = require('https');
const httpsAgent = new https.Agent({
keepAlive: true,
});
export const fetch_retry = async (
url: string,
options: any = null,
useHttpKeepAlive: boolean = true,
retryCount: number = 2,
) => {
try {
// options are optional, let's default to a GET if not provided
if (!options) {
options = { method: 'GET' };
}
// http keep alive allows us to re-use connections for faster calls, use it if we can
if (useHttpKeepAlive && !options.agent) {
options.agent = httpsAgent;
}
// run the fetch like normal
return await fetch(url, options);
} catch (err) {
// an error occurred with the fetch. Could be a normal error, could be a keep alive
console.log('An error occurred with fetch: ', err);
// if we are down to our last retry count, just throw the error and don't try again
if (retryCount === 1) throw err;
console.log(`Attempting to retry fetch. RetryCount: ${retryCount}`);
// recursively call this function again, decrementing the retryCount
// do a fresh https agent without keep alive to increase chance of getting it returned
return await fetch_retry(url, options, false, retryCount - 1);
}
};
// example usage
/*
import { fetch_retry } from "./fetch-retry-helper";
export class YourService {
async GetDataFromAnApi(url: string): Promise<any> {
const response = await fetch_retry(url);
return response.json();
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment