Objects
GraphQL objects represent a list of named fields, each of which yield a value of a specific type.
When declaring a GraphQL schema, most of the time we deal with GraphQL objects, because they are the only place where we actually define the behavior once schema gets executed.
There are two ways to define a GraphQL object in Juniper:
- The easiest way, suitable for trivial cases, is to use the
#[derive(GraphQLObject)]
attribute on a struct, as described below. - The other way, using the
#[graphql_object]
attribute, is described in the "Complex fields" chapter.
Trivial
While any type in Rust can be exposed as a GraphQL object, the most common one is a struct:
This creates a GraphQL object type called Person
, with two fields: name
of type String!
, and age
of type Int!
. Because of Rust's type system, everything is exported as non-null
by default.
TIP: If a
null
able field is required, the most obvious way is to useOption
. OrNullable
for distinguishing between explicit and implicitnull
s.
Documentation
We should take advantage of the fact that GraphQL is self-documenting and add descriptions to the defined GraphQL object type and its fields. Juniper will automatically use associated Rust doc comments as GraphQL descriptions:
If using Rust doc comments is not desired (for example, when we want to keep Rust API docs and GraphQL schema descriptions different), the #[graphql(description = "...")]
attribute can be used instead, which takes precedence over Rust doc comments:
Renaming
By default, struct fields are converted from Rust's standard snake_case
naming convention into GraphQL's camelCase
convention:
We can override the name by using the #[graphql(name = "...")]
attribute:
Or provide a different renaming policy for all the struct fields:
TIP: Supported policies are:
SCREAMING_SNAKE_CASE
,camelCase
andnone
(disables any renaming).
Deprecation
To deprecate a GraphQL object field, either the #[graphql(deprecated = "...")]
attribute, or Rust's #[deprecated]
attribute, should be used:
NOTE: Only GraphQL object/interface fields and GraphQL enum values can be deprecated.
Ignoring
By default, all struct fields are included into the generated GraphQL object type. To prevent inclusion of a specific field annotate it with the #[graphql(ignore)]
attribute:
TIP: See more available features in the API docs of the
#[derive(GraphQLObject)]
attribute.
Relationships
GraphQL object fields can be of any GraphQL type, except input objects.
Let's see what it means to build relationships between objects:
Because Person
is a valid GraphQL type, we can have a Vec<Person>
in a struct, and it'll be automatically converted into a list of non-null
able Person
objects.