Last active
December 4, 2018 15:45
-
-
Save drejohnson/df68ec8b5dd83ee83c1639565c061a3c to your computer and use it in GitHub Desktop.
Using async generators and fetch api to query graphql
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
export const initGraphql = (input: RequestInfo, accessKey?: string) => | |
async function* asyncFetch(query: any, variables?: any) { | |
while (true) { | |
const response = await fetch(input, { | |
method: 'POST', | |
headers: accessKey | |
? { | |
'Content-Type': 'application/json', | |
'x-hasura-access-key': accessKey, | |
} | |
: undefined, | |
body: JSON.stringify({ | |
query, | |
variables, | |
}), | |
cache: 'force-cache', | |
}) | |
const responseJSON = await response.json() | |
if (responseJSON) yield responseJSON | |
else return | |
} | |
} | |
export const request = initGraphql( | |
process.env.GRAPHQL_ENDPOINT as string, | |
process.env.HASURA_ACCESS_KEY as string, | |
) | |
async function example() { | |
for await (const { data } of request(my_graphql_query)) { | |
console.log(data) | |
if (data) break | |
} | |
} | |
example() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment