Skip to content

Custom queries & fragments

Afosto allows developers to craft custom GraphQL queries and mutations, giving them greater control and flexibility when interacting with the Afosto API. Fragments can also be used to select and reuse a set of fields across different queries and mutations.

Custom Queries

Queries are used to fetch data from your Afosto API. Below is an example of how you can use a custom query:

```js
import { gql } from '@afosto/storefront';

// Write your query
const query = gql`
  query getCart($id: String!) {
    cart(id: $id) {
      subtotal
      total
      items {
        ids
        image
        label
        sku
      }
    }
  }
`;

// Define your variables
const variables = {
  id: 'my_cart_token',
};

// Execute the query
const response = await client.query(query, variables);

## Custom Mutations

Mutations are used to change data in your Afosto API. Below is an example of how to use a custom mutation:

import StorefrontClient, { gql } from '@afosto/storefront';

const client = StorefrontClient({
  storefrontToken: 'STOREFRONT_TOKEN',
});

// Write your mutation
const mutation = gql`
  mutation AddPhoneNumberToCart($add_phone_number_to_cart: AddPhoneNumberToCartInput!) {
    AddPhoneNumberToCartInput(input: $add_phone_number_to_cart) {
      cart {
        phone_number {
          id
          country_code
          number
          national
          type
          created_at
        }
      }
    }
  }
`;

// Define your variables
const variables = {
  AddPhoneNumberToCartInput: {
    cartId: currentCartToken,
  },
};

// Execute the mutation
const response = await client.query(mutation, variables);

## Custom Fragments

Fragments are reusable units that define a set of fields you want to include in your queries or mutations. The [@afosto/storefront](https://github.com/afosto/storefront) package exports all fragments used in the client. You can check these out at [Afosto Storefront Fragments](https://github.com/afosto/storefront/tree/main/src/fragments) as inspiration for your own fragments.

import { gql } from '@afosto/graphql-client';

// Define your fragment
const CustomCartFragment = gql`
  fragment CustomCartFragment on Cart {
    total
    total_excluding_vat
    ... other fields
  }
`;

// Write your query with the fragment
const query = gql`
	${CustomCartFragment}
  query getCart($id: String!) {
    cart(id: $id) {
      ...CustomCartFragment
    }
  }
`;

// Define your variables
const variables = {
  id: client.getCartTokenFromStorage(),
};

// Execute the query
const response = await client.query(query, variables);

## Exploring Queries and Mutations

You can explore and test your queries and mutations on the Afosto GraphQL playground at [https://afosto.app/graphql](https://afosto.app/graphql). Here you can browse through the schema and docs, and test your queries and mutations.

Related documentation