Skip to content

Instantly share code, notes, and snippets.

@dougg0k
Created July 29, 2022 19:02
Show Gist options
  • Select an option

  • Save dougg0k/91e3b66d557532789ef74a4499794ce0 to your computer and use it in GitHub Desktop.

Select an option

Save dougg0k/91e3b66d557532789ef74a4499794ce0 to your computer and use it in GitHub Desktop.
import { GraphQLClient, RequestDocument, Variables } from "graphql-request";
export function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function gqlRequest({
url,
document,
variables,
additionalHeaders = {},
retries = 5,
}: {
url: string;
document: RequestDocument;
variables?: Variables;
additionalHeaders?: Record<string, any>;
retries?: number;
}) {
const gqlClient = new GraphQLClient(url, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
...additionalHeaders,
},
cache: "no-cache",
method: "POST",
});
return await gqlRetrify(gqlClient.request(document, variables), {
retries,
});
}
async function gqlRetrify(
requestPromise: Promise<any>,
{ retries = 3, everyMs = 1_000 },
retriesCount = 0,
) {
try {
return await requestPromise;
} catch (err) {
if (retriesCount >= retries) {
throw err;
}
await delay(everyMs);
return await gqlRetrify(
requestPromise,
{ retries, everyMs },
retriesCount + 1,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment