Created
July 29, 2022 19:02
-
-
Save dougg0k/91e3b66d557532789ef74a4499794ce0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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