Jan 21, 2019 · Updated: Jul 12, 2021 · by Tim Kamanin
If you're reading this, probably you know how awesome (or painful) GraphQL is. Since we're all developers here and one of our mantras is DRY (which stands for ... well you know what it means, don't you?) we might cringe a little bit when we see repeating parts in our GraphQL queries.
Consider the following GraphQL query/mutation pair that fetches and updates a product:
export const GET_PRODUCT = gql`
query getProduct($id: ID!) {
product(id: $id) {
id
title
description
image
price
}
}
`;
export const UPDATE_PRODUCT = gql`
mutation productUpdate($product: ProductInput!) {
productUpdate(input: $product) {
product {
id
title
description
image
price
}
}
}
`;
I guess we both agree there's a repeating part that begs us to get extracted:
{
id
title
description
image
price
}
It turns out that GraphQL people are also smart and they had the same awkward feeling. Thus they created a thing that allows us to extract a fragment of a query and re-use it in another query. And they called the thing (drumroll please) Fragments.
Here's how we can define a fragment in JS/React code:
export const PRODUCT_DETAILS_FRAGMENT = gql`
fragment ProductDetails on Product {
id
title
description
image
price
}
`;
Where
So now we can simplify our query/mutation pair to:
export const GET_PRODUCT = gql`
query getProduct($id: ID!) {
product(id: $id) {
...ProductDetails
}
}
${PRODUCT_DETAILS_FRAGMENT}
`;
export const UPDATE_PRODUCT = gql`
mutation productUpdate($product: ProductInput!) {
productUpdate(input: $product) {
product {
...ProductDetails
}
}
}
${PRODUCT_DETAILS_FRAGMENT}
`;
Please note how we inject our fragment into query/mutation:
We add a fragment to a place where we'd typically describe a product output:
product {
...ProductDetails
}
Don't miss the ...
in front of the ProductDetails
.
We inject ${PRODUCT_DETAILS_FRAGMENT}
at the end of the query/mutation, so GraphQL knows where to look for a ProductDetails
fragment.
And that's all! Now you know this powerful technique to make your GraphQL codebase more DRY and organized. Enjoy and let me know in the comments below if that helped you.
Hey, if you've found this useful, please share the post to help other folks find it: