Faça queries e mutations diretamente com fetch(). Nenhuma dependência necessária.
Crie uma função reutilizável para todas as chamadas GraphQL:
const graphql = async (query, variables = {}) => {
const response = await fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
credentials: 'include'
});
const json = await response.json();
if (json.errors) throw new Error(json.errors[0].message);
return json.data;
};
const data = await graphql(`{
client(hostname: "minhaloja") {
products(first: 10) {
edges {
node {
id
title
price
images { url }
}
}
}
}
}`);
const products = data.client.products.edges.map(e => e.node); const data = await graphql(
`mutation($input: AddShoppingCartItemMutationInput!) {
addShoppingCartItem(input: $input) {
shoppingCart {
totalPrice
products { title quantity price }
}
}
}`,
{
input: {
hostname: "minhaloja",
productId: "product-id-here",
quantity: 1
}
}
); const data = await graphql(`{
shoppingCart(hostname: "minhaloja") {
totalPrice
originalTotalPrice
products {
id title price quantity
images { url }
}
coupon { code discount }
}
}`);
const data = await graphql(`{
client(hostname: "minhaloja") {
storeInfo {
name
images { url }
}
menus {
edges { node { id title link } }
}
}
}`);
MutationInput. Exemplo: AddShoppingCartItemMutationInput, ClientLoginMutationInput. Use o GraphQL Explorer para ver os campos exatos de cada tipo.
Todos os templates e o SDK incluem um script para baixar o schema atualizado via introspection:
npm run update # Faz introspection na API e gera schema.graphql