The following executes correctly in graphiQL
fragment BookGridFields on Book {
_id
title
}
{
allBooks {
...BookGridFields
}
}
My question is, it possible to specify the fragment right in my schema, right below where my Book type is defined, like so
type Book {
_id: String
title: String
pages: Int
weight: Float
authors: [Author]
}
fragment BookGridFields on Book {
_id
title
}
So that I could just run queries like this
{
allBooks {
...BookGridFields
}
}
without needing to define the fragment as part of my query.
Currently the above errors with
Unknown fragment \"BookGridFields\"
A GraphQL fragment is a piece of logic that can be shared between multiple queries and mutations. Every fragment includes a subset of the fields that belong to its associated type. In the above example, the Person type must declare firstName and lastName fields for the NameParts fragment to be valid.
A fragment is basically a reusable piece of query. In GraphQL, you often need to query for the same data fields in different queries. The code to define these fields has to be written multiple times, leading to more errors.
GraphQL in Action MEAP V05 Inline fragments are, in a way, similar to anonymous functions that you can use without a name. They are just fragments without names and you can spread them inline where you define them.
The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).
Per the graphql docs, I see that fragments are a part of the query api and not valid syntax for setting up a schema. This leads me to conclude that it is not currently possible to specify a fragment in a schema.
https://graphql.org/learn/queries/#fragments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With