[−][src]Attribute Macro async_graphql::Interface
#[Interface]
Define a GraphQL interface
Macro parameters
Attribute | description | Type | Optional |
---|---|---|---|
name | Object name | string | Y |
desc | Object description | string | Y |
Field parameters
Attribute | description | Type | Optional |
---|---|---|---|
name | Field name | string | N |
type | Field type | string | N |
desc | Field description | string | Y |
method | Field method name | string | Y |
context | Method with the context | string | Y |
deprecation | Field deprecation reason | string | Y |
args | Field arguments | [Arg] | Y |
Field argument parameters
Attribute | description | Type | Optional |
---|---|---|---|
name | Argument name | string | N |
type | Argument type | string | N |
desc | Argument description | string | Y |
default | Argument default value | string | Y |
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, GQLEmptyMutation).data("hello".to_string()); let res = schema.query(r#" { type_a { value_a value_b value_c(a: 3, b: 2) } }"#).execute().await.unwrap(); assert_eq!(res, serde_json::json!({ "type_a": { "value_a": "hello", "value_b": 10, "value_c": 5 } })); }