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:
1import { gql } from '@afosto/storefront';
2
3// Write your query
4const query = gql`
5 query getCart($id: String!) {
6 cart(id: $id) {
7 subtotal
8 total
9 items {
10 ids
11 image
12 label
13 sku
14 }
15 }
16 }
17`;
18
19// Define your variables
20const variables = {
21 id: 'my_cart_token',
22};
23
24// Execute the query
25const 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:
1import StorefrontClient, { gql } from '@afosto/storefront';
2
3const client = StorefrontClient({
4 storefrontToken: 'STOREFRONT_TOKEN',
5});
6
7// Write your mutation
8const mutation = gql`
9 mutation AddPhoneNumberToCart($add_phone_number_to_cart: AddPhoneNumberToCartInput!) {
10 AddPhoneNumberToCartInput(input: $add_phone_number_to_cart) {
11 cart {
12 phone_number {
13 id
14 country_code
15 number
16 national
17 type
18 created_at
19 }
20 }
21 }
22 }
23`;
24
25// Define your variables
26const variables = {
27 AddPhoneNumberToCartInput: {
28 cartId: currentCartToken,
29 },
30};
31
32// Execute the mutation
33const 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 package exports all fragments used in the client. You can check these out at Afosto Storefront Fragments as inspiration for your own fragments.
1import { gql } from '@afosto/graphql-client';
2
3// Define your fragment
4const CustomCartFragment = gql`
5 fragment CustomCartFragment on Cart {
6 total
7 total_excluding_vat
8 ... other fields
9 }
10`;
11
12// Write your query with the fragment
13const query = gql`
14 ${CustomCartFragment}
15 query getCart($id: String!) {
16 cart(id: $id) {
17 ...CustomCartFragment
18 }
19 }
20`;
21
22// Define your variables
23const variables = {
24 id: client.getCartTokenFromStorage(),
25};
26
27// Execute the query
28const 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. Here you can browse through the schema and docs, and test your queries and mutations.