JAVASCRIPT
Performing GraphQL Mutations with Vanilla JavaScript
Execute GraphQL mutations using vanilla JavaScript and the fetch API to create, update, or delete data, providing direct interaction with your GraphQL backend.
async function performGraphQLMutation(graphqlEndpoint, mutation, variables = {}) {
try {
const response = await fetch(graphqlEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Add if authentication is required
},
body: JSON.stringify({
query: mutation,
variables: variables
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorText}`);
}
const result = await response.json();
if (result.errors) {
console.error('GraphQL Errors:', result.errors);
throw new Error('GraphQL error occurred: ' + result.errors.map(err => err.message).join(', '));
}
return result.data;
} catch (error) {
console.error('Error performing GraphQL mutation:', error);
throw error;
}
}
// Example Usage:
const GRAPHQL_API_URL = 'https://your-graphql-api.com/graphql'; // Replace with your GraphQL endpoint
// 1. Create a new post
const createPostMutation = `
mutation CreateNewPost($title: String!, $content: String!) {
createPost(title: $title, content: $content) {
id
title
content
author { id name }
}
}
`;
async function createPost() {
try {
const data = await performGraphQLMutation(
GRAPHQL_API_URL,
createPostMutation,
{ title: 'My New Article', content: 'This is the content of my new article.' }
);
console.log('New post created:', data.createPost);
} catch (error) {
console.error('Failed to create post:', error);
}
}
// 2. Update an existing user's email
const updateUserEmailMutation = `
mutation UpdateUserEmail($id: ID!, $email: String!) {
updateUser(id: $id, email: $email) {
id
name
email
}
}
`;
async function updateUser() {
try {
const data = await performGraphQLMutation(
GRAPHQL_API_URL,
updateUserEmailMutation,
{ id: 'user123', email: '[email protected]' }
);
console.log('User email updated:', data.updateUser);
} catch (error) {
console.error('Failed to update user:', error);
}
}
// Execute the example mutations
createPost();
updateUser();
How it works: This snippet demonstrates how to perform GraphQL mutations using vanilla JavaScript's `fetch` API. Unlike queries which fetch data, mutations are used to modify data on the server (create, update, delete). The mutation string, along with any necessary variables, is sent in the `body` of a `POST` request as a JSON object. The `Content-Type` header must be set to `application/json`. The function handles both network errors and GraphQL-specific errors returned in the `errors` array of the response, ensuring robust interaction with your GraphQL backend.