[][src]Attribute Macro async_graphql::Interface

#[Interface]

Define a GraphQL interface

Macro parameters

AttributedescriptionTypeOptional
nameObject namestringY
descObject descriptionstringY

Field parameters

AttributedescriptionTypeOptional
nameField namestringN
typeField typestringN
descField descriptionstringY
contextMethod with the contextstringY
deprecationField deprecation reasonstringY
argsField argumentsY

Field argument parameters

AttributedescriptionTypeOptional
nameArgument namestringN
typeArgument typestringN
descArgument descriptionstringY
defaultArgument default valuestringY

Define an interface

Define TypeA, TypeB, TypeC... Implement the MyInterface

This example is not tested
#[Interface]
struct MyInterface(TypeA, TypeB, TypeC, ...);

Fields

The type, name, and parameters of the interface field must exactly match the type that implements the interface, The internal implementation is a forward of the function call. You can specify the field function name that implements the interface type through the 'method' property, or you can specify that the field function has a context parameter through the 'context' attribute.

use async_graphql::*;

struct TypeA {
    value: i32,
}

#[Object]
impl TypeA {
    /// Returns data borrowed from the context
    #[field]
    async fn value_a<'a>(&self, ctx: &'a Context<'_>) -> &'a str {
        ctx.data::<String>().as_str()
    }

    /// Returns data borrowed self
    #[field]
    async fn value_b(&self) -> &i32 {
        &self.value
    }

    /// With parameters
    #[field]
    async fn value_c(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

#[Interface(
    field(name = "value_a", type = "&'ctx str", context),
    field(name = "value_b", type = "&i32"),
    field(name = "value_c", type = "i32",
        arg(name = "a", type = "i32"),
        arg(name = "b", type = "i32")),
)]
struct MyInterface(TypeA);

struct QueryRoot;

#[Object]
impl QueryRoot {
    #[field]
    async fn type_a(&self) -> MyInterface {
        TypeA { value: 10 }.into()
    }
}

#[async_std::main]
async fn main() {
    let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription).data("hello".to_string());
    let res = schema.query(r#"
    {
        typeA {
            valueA
            valueB
            valueC(a: 3, b: 2)
        }
    }"#).execute().await.unwrap().data;
    assert_eq!(res, serde_json::json!({
        "typeA": {
            "valueA": "hello",
            "valueB": 10,
            "valueC": 5
        }
    }));
}