Skip to content

Instantly share code, notes, and snippets.

@drejohnson
Last active December 4, 2018 15:45
Show Gist options
  • Save drejohnson/df68ec8b5dd83ee83c1639565c061a3c to your computer and use it in GitHub Desktop.
Save drejohnson/df68ec8b5dd83ee83c1639565c061a3c to your computer and use it in GitHub Desktop.
Using async generators and fetch api to query graphql
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