async function queryGraphQL(endpoint, query, variables = {}) { try { const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', // 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Uncomment and add if your GraphQL API requires authentication }, body: JSON.stringify({ query, variables }) }); if (!response.ok) { throw new Error(`Network response was not ok: ${response.statusText}`); } const result = await response.json(); if (result.errors) { console.error('GraphQL Errors:', result.errors); throw new Error(result.errors.map(err => err.message).join(' ')); } return result.data; } catch (error) { console.error('GraphQL query failed:', error); throw error; } } // Example Usage: // const graphqlEndpoint = 'https://api.example.com/graphql'; // const GET_USER_QUERY = ` // query GetUser($id: ID!) { // user(id: $id) { // id // name // email // } // } // `; // // const variables = { id: "user123" }; // // queryGraphQL(graphqlEndpoint, GET_USER_QUERY, variables) // .then(data => console.log('GraphQL User Data:', data.user)) // .catch(error => console.error('GraphQL Query Error:', error)); // // const ADD_POST_MUTATION = ` // mutation AddPost($title: String!, $content: String!) { // addPost(title: $title, content: $content) { // id // title // } // } // `; // // const postVariables = { title: "My First Post", content: "This is the content of my first post." }; // queryGraphQL(graphqlEndpoint, ADD_POST_MUTATION, postVariables) // .then(data => console.log('New Post Added:', data.addPost)) // .catch(error => console.error('GraphQL Mutation Error:', error));