Skip to content

Instantly share code, notes, and snippets.

@dotansimha
Last active November 19, 2023 12:17
Show Gist options
  • Save dotansimha/247782206d00541aee6e8d8bd21f9997 to your computer and use it in GitHub Desktop.
Save dotansimha/247782206d00541aee6e8d8bd21f9997 to your computer and use it in GitHub Desktop.
GraphQL wrapper for `fetch` (based on `TypedDocumentNode`)
async function fetchGraphQL<TResult, TVariables>(
operation: TypedDocumentNode<TResult, TVariables>,
...[variables]: TVariables extends Record<string, never> ? [] : [TVariables]
): Promise<TResult> {
const response = await fetch("http://MY-SERVER/graphql", {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
method: 'POST',
body: JSON.stringify({
query: typeof operation === 'string' ? operation : print(operation),
variables,
}),
});
if (!response.ok) {
throw new Error(`Invalid GraphQL status code: ${response.status}`);
}
const jsonData = (await response.json()) as ExecutionResult<TResult>;
if (jsonData.errors && jsonData.errors.length > 0) {
throw new Error(
`Failed to execute GraphQL operation: ${jsonData.errors
.map(e => e.message)
.join('\n')}`
);
}
return jsonData.data!;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment