GraphQL Fetch Helper
Simplify making GraphQL requests with a reusable fetch helper.
Interacting with GraphQL APIs often involves sending POST requests with a query and variables. This helper encapsulates the boilerplate and error handling so you can focus on your queries. It returns the data
field on success and throws if the response contains errors or an HTTP error status.
export async function gqlRequest<T>(
endpoint: string,
query: string,
variables: Record<string, unknown> = {}
) {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const result = (await response.json()) as { data?: T; errors?: unknown };
if (result.errors) {
throw new Error(`GraphQL errors: ${JSON.stringify(result.errors)}`);
}
return result.data as T;
}
// Example usage:
// const query = `query User($id: ID!) { user(id: $id) { id name email } }`;
// const data = await gqlRequest<{ user: { id: string; name: string } }>(
// '/graphql',
// query,
// { id: '1' }
// );
This helper hides the repetitive parts of GraphQL fetch calls and provides typed responses in TypeScript. You can extend it with authentication headers, retries, or caching as needed.