[−][src]Macro juniper::graphql_interface
Expose GraphQL interfaces
Mapping interfaces to GraphQL can be tricky: there is no direct counterpart to GraphQL interfaces in Rust, and downcasting is not possible in the general case. Many other GraphQL implementations in other languages use instance checks and either dynamic typing or forced downcasts to support these features.
A GraphQL interface defines fields that the implementing types also need to implement. A GraphQL interface also needs to be able to determine the concrete type name as well as downcast the general type to the actual concrete type.
Syntax
See the documentation for graphql_object!
on the general item and type
syntax. graphql_interface!
requires an additional instance_resolvers
item,
and does not support the interfaces
item.
instance_resolvers
is a match like structure used to resolve the concrete
instance type of the interface. It starts with a context argument and continues
with a number of match arms; on the left side is the indicated type, and on the
right an expression that resolve into Option<T>
of the type indicated:
instance_resolvers: |&context| { &Human => context.get_human(self.id()), // returns Option<&Human> &Droid => context.get_droid(self.id()), // returns Option<&Droid> },
This is used for both the __typename
field and when resolving a specialized
fragment, e.g. ...on Human
. For __typename
, the resolvers will be executed
in order - the first one returning Some
will be the determined type name. When
resolving fragment type conditions, only the corresponding match arm will be
executed.
Example
A simplified extract from the StarWars schema example shows how to use the shared context to implement downcasts.
struct Human { id: String } struct Droid { id: String } struct Database { humans: HashMap<String, Human>, droids: HashMap<String, Droid>, } trait Character { fn id(&self) -> &str; } impl Character for Human { fn id(&self) -> &str { &self.id } } impl Character for Droid { fn id(&self) -> &str { &self.id } } graphql_object!(Human: Database as "Human" |&self| { field id() -> &str { &self.id } }); graphql_object!(Droid: Database as "Droid" |&self| { field id() -> &str { &self.id } }); // You can introduce lifetimes or generic parameters by < > before the name. graphql_interface!(<'a> &'a Character: Database as "Character" |&self| { field id() -> &str { self.id() } instance_resolvers: |&context| { &Human => context.humans.get(self.id()), &Droid => context.droids.get(self.id()), } });