Macro juniper::graphql_object [] [src]

macro_rules! graphql_object {
    ( @as_item, $i:item) => { ... };
    ( @as_expr, $e:expr) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
        field deprecated $reason:tt $name:ident $args:tt -> $t:ty as $desc:tt $body:block $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
        field deprecated $reason:tt $name:ident $args:tt -> $t:ty $body:block $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
        field $name:ident $args:tt -> $t:ty as $desc:tt $body:block $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
        field $name:ident $args:tt -> $t:ty $body:block $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
        description : $value:tt $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
        interfaces : $value:tt $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr, , $( $rest:tt )*
    ) => { ... };
    (
        @gather_object_meta,
        $reg:expr, $acc:expr, $descr:expr, $ifaces:expr,
    ) => { ... };
    ( @assign_interfaces, $reg:expr, $tgt:expr, [ $($t:ty,)* ] ) => { ... };
    ( @assign_interfaces, $reg:expr, $tgt:expr, [ $($t:ty),* ] ) => { ... };
    (
        ( $($lifetime:tt)* );
        $name:ty; $ctxt:ty; $outname:expr; $mainself:ident; $($items:tt)*
    ) => { ... };
    (
        <$( $lifetime:tt ),*> $name:ty : $ctxt:ty as $outname:tt | &$mainself:ident | {
            $( $items:tt )*
        }
    ) => { ... };
    (
        $name:ty : $ctxt:ty as $outname:tt | &$mainself:ident | {
            $( $items:tt )*
        }
    ) => { ... };
    (
        $name:ty : $ctxt:ty | &$mainself:ident | {
            $( $items:tt )*
        }
    ) => { ... };
}

Expose GraphQL objects

This is a short-hand macro that implements the GraphQLType trait for a given type. By using this macro instead of implementing it manually, you gain type safety and reduce repetitive declarations.

Examples

The simplest case exposes fields on a struct:

struct User { id: String, name: String, group_ids: Vec<String> }

graphql_object!(User: () |&self| {
    field id() -> &String {
        &self.id
    }

    field name() -> &String {
        &self.name
    }

    // Field and argument names will be converted from snake case to camel case,
    // as is the common naming convention in GraphQL. The following field would
    // be named "memberOfGroup", and the argument "groupId".
    field member_of_group(group_id: String) -> bool {
        self.group_ids.iter().any(|gid| gid == &group_id)
    }
});

Documentation and descriptions

You can optionally add descriptions to the type itself, the fields, and field arguments:

struct User { id: String, name: String, group_ids: Vec<String> }

graphql_object!(User: () |&self| {
    description: "A user in the database"

    field id() -> &String as "The user's unique identifier" {
        &self.id
    }

    field name() -> &String as "The user's name" {
        &self.name
    }

    field member_of_group(
        group_id: String as "The group id you want to test membership against"
    ) -> bool as "Test if a user is member of a group" {
        self.group_ids.iter().any(|gid| gid == &group_id)
    }
});

Generics and lifetimes

You can expose generic or pointer types by prefixing the type with the necessary generic parameters:

trait SomeTrait { fn id(&self) -> &str; }

graphql_object!(<'a> &'a SomeTrait: () as "SomeTrait" |&self| {
    field id() -> &str { self.id() }
});

struct GenericType<T> { items: Vec<T> }

graphql_object!(<T> GenericType<T>: () as "GenericType" |&self| {
    field count() -> i32 { self.items.len() as i32 }
});

Implementing interfaces

You can use the interfaces item to implement interfaces:

trait Interface {
    fn id(&self) -> &str;
    fn as_implementor(&self) -> Option<Implementor>;
}
struct Implementor { id: String }

graphql_interface!(<'a> &'a Interface: () as "Interface" |&self| {
    field id() -> &str { self.id() }

    instance_resolvers: |&context| {
        Implementor => self.as_implementor(),
    }
});

graphql_object!(Implementor: () |&self| {
    field id() -> &str { &self.id }

    interfaces: [&Interface]
});

Note that the implementing type does not need to implement the trait on the Rust side - only what's in the GraphQL schema matters. The GraphQL interface doesn't even have to be backed by a trait!

Emitting errors

FieldResult<T> is a simple type alias for Result<T, String>. In the end, errors that fields emit are serialized into strings in the response. However, the execution system will keep track of the source of all errors, and will continue executing despite some fields failing.

struct User { id: String }

graphql_object!(User: () |&self| {
    field id() -> FieldResult<&String> {
        Ok(&self.id)
    }

    field name() -> FieldResult<&String> {
        Err("Does not have a name".to_owned())
    }
});

Syntax

The top-most syntax of this macro defines which type to expose, the context type, which lifetime parameters or generics to define, and which name to use in the GraphQL schema. It takes one of the following two forms:

ExposedType: ContextType as "ExposedName" |&self| { items... }
<Generics> ExposedType: ContextType as "ExposedName" |&self| { items... }

Items

Each item within the brackets of the top level declaration has its own syntax. The order of individual items does not matter. graphql_object! supports a number of different items.

Top-level description

description: "Top level description"

Adds documentation to the type in the schema, usable by tools such as GraphiQL.

Interfaces

interfaces: [&Interface, ...]

Informs the schema that the type implements the specified interfaces. This needs to be GraphQL interfaces, not necessarily Rust traits. The Rust types do not need to have any connection, only what's exposed in the schema matters.

Fields

field name(args...) -> Type { }
field name(args...) -> Type as "Field description" { }
field deprecated "Reason" name(args...) -> Type { }
field deprecated "Reason" name(args...) -> Type as "Field description" { }

Defines a field on the object. The name is converted to camel case, e.g. user_name is exposed as userName. The as "Field description" adds the string as documentation on the field.

Field arguments

&executor
arg_name: ArgType
arg_name = default_value: ArgType
arg_name: ArgType as "Argument description"
arg_name = default_value: ArgType as "Argument description"

Field arguments can take many forms. If the field needs access to the executor or context, it can take an Executor instance by specifying &executor as the first argument.

The other cases are similar to regular Rust arguments, with two additions: argument documentation can be added by appending as "Description" after the type, and a default value can be specified by appending = value after the argument name.

Arguments are required (i.e. non-nullable) by default. If you specify either a default value, or make the type into an Option<>, the argument becomes optional. For example:

arg_name: i32               -- required
arg_name: Option<i32>       -- optional, None if unspecified
arg_name = 123: i32         -- optional, "123" if unspecified

Due to some syntactical limitations in the macros, you must parentesize more complex default value expressions:

arg_name = (Point { x: 1, y: 2 }): Point
arg_name = ("default".to_owned()): String