Derive Macro async_graphql::Union[][src]

#[derive(Union)]
{
    // Attributes available to this derive:
    #[graphql]
}

Define a GraphQL union

See also the Book.

Macro parameters

AttributedescriptionTypeOptional
nameObject namestringY
visibleIf false, it will not be displayed in introspection. See also the Book.boolY
visibleCall the specified function. If the return value is false, it will not be displayed in introspection.stringY

Item parameters

AttributedescriptionTypeOptional
flattenSimilar to serde (flatten)booleanY

Define a union

Define TypeA, TypeB, … as MyUnion

use async_graphql::*;

#[derive(SimpleObject)]
struct TypeA {
    value_a: i32,
}

#[derive(SimpleObject)]
struct TypeB {
    value_b: i32
}

#[derive(Union)]
enum MyUnion {
    TypeA(TypeA),
    TypeB(TypeB),
}

struct QueryRoot;

#[Object]
impl QueryRoot {
    async fn all_data(&self) -> Vec<MyUnion> {
        vec![TypeA { value_a: 10 }.into(), TypeB { value_b: 20 }.into()]
    }
}

tokio::runtime::Runtime::new().unwrap().block_on(async move {
    let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).data("hello".to_string()).finish();
    let res = schema.execute(r#"
    {
        allData {
            ... on TypeA {
                valueA
            }
            ... on TypeB {
                valueB
            }
        }
    }"#).await.into_result().unwrap().data;
    assert_eq!(res, value!({
        "allData": [
            { "valueA": 10 },
            { "valueB": 20 },
        ]
    }));
});