Macro juniper::graphql_scalar [] [src]

macro_rules! graphql_scalar {
    ( @maybe_apply, None, $func:ident, $val:expr ) => { ... };
    ( @maybe_apply, $arg:tt, $func:ident, $val:expr ) => { ... };
    (
        @generate,
        ( $name:ty, $outname:tt, $descr:tt ),
        (
            ( $resolve_selfvar:ident, $resolve_body:block ),
            ( $fiv_arg:ident, $fiv_result:ty, $fiv_body:block )
        )
    ) => { ... };
    (
        @parse,
        $meta:tt,
        $acc:tt,
    ) => { ... };
    (
        @parse,
        $meta:tt,
        ( $_ignored:tt, $fiv:tt ),
        resolve(&$selfvar:ident) -> Value $body:block $($rest:tt)*
    ) => { ... };
    (
        @parse,
        $meta:tt,
        ( $resolve:tt, $_ignored:tt ),
        from_input_value($arg:ident: &InputValue) -> $result:ty $body:block $($rest:tt)*
    ) => { ... };
    (
        @parse,
        ( $name:ty, $outname:tt, $_ignored:tt ),
        $acc:tt,
        description: $descr:tt $($rest:tt)*
    ) => { ... };
    ( $name:ty as $outname:tt { $( $items:tt )* }) => { ... };
    ( $name:ty { $( $items:tt )* }) => { ... };
}

Expose GraphQL scalars

The GraphQL language defines a number of built-in scalars: strings, numbers, and booleans. This macro can be used either to define new types of scalars (e.g. timestamps), or expose other types as one of the built-in scalars (e.g. bigints as numbers or strings).

Since the preferred transport protocol for GraphQL responses is JSON, most custom scalars will be transferred as strings. You therefore need to ensure that the client library you are sending data to can parse the custom value into a datatype appropriate for that platform.

struct UserID(String);

graphql_scalar!(UserID {
    description: "An opaque identifier, represented as a string"

    resolve(&self) -> Value {
        Value::string(&self.0)
    }

    from_input_value(v: &InputValue) -> Option<UserID> {
        v.as_string_value().map(|s| UserID(s.to_owned()))
    }
});

In addition to implementing GraphQLType for the type in question, FromInputValue and ToInputValue is also implemented. This makes the type usable as arguments and default values.