Last active
November 19, 2023 12:17
-
-
Save dotansimha/247782206d00541aee6e8d8bd21f9997 to your computer and use it in GitHub Desktop.
GraphQL wrapper for `fetch` (based on `TypedDocumentNode`)
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
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