[][src]Attribute Macro async_graphql::Object

#[Object]

Define a GraphQL object

Macro parameters

AttributedescriptionTypeOptional
nameObject namestringY
descObject descriptionstringY
cache_controlObject cache controlCacheControlY

Field parameters

AttributedescriptionTypeOptional
nameField namestringY
descField descriptionstringY
deprecationField deprecation reasonstringY
cache_controlField cache controlCacheControlY

Field argument parameters

AttributedescriptionTypeOptional
nameArgument namestringY
descArgument descriptionstringY
defaultArgument default valuestringY
validatorInput value validatorInputValueValidatorY

The field returns the value type

  • A scalar value, such as i32, bool
  • Borrowing of scalar values, such as &i32, &bool
  • Vec, such as Vec<i32>
  • Slice, such as &[i32]
  • Option, such as Option<i32>
  • Object and &Object
  • Enum
  • Result<T, E>, such as Result<i32, E>

Context

You can define a context as an argument to a method, and the context should be the first argument to the method.

This example is not tested
#[Object]
impl MyObject {
    async fn value(&self, ctx: &Context<'_>) -> { ... }
}

Examples

use async_graphql::*;

struct MyObject {
    value: i32,
}

#[Object]
impl MyObject {
    #[field(desc = "value")]
    async fn value(&self) -> i32 {
        self.value
    }

    #[field(desc = "reference value")]
    async fn value_ref(&self) -> &i32 {
        &self.value
    }

    #[field(desc = "value with error")]
    async fn value_with_error(&self) -> Result<i32> {
        Ok(self.value)
    }

    #[field]
    async fn value_with_arg(&self, #[arg(default = "1")] a: i32) -> i32 {
        a
    }
}

#[async_std::main]
async fn main() {
    let schema = Schema::new(MyObject{ value: 10 }, EmptyMutation, EmptySubscription);
    let res = schema.query(r#"{
        value
        valueRef
        valueWithError
        valueWithArg1: valueWithArg
        valueWithArg2: valueWithArg(a: 99)
    }"#).execute().await.unwrap().data;
    assert_eq!(res, serde_json::json!({
        "value": 10,
        "valueRef": 10,
        "valueWithError": 10,
        "valueWithArg1": 1,
        "valueWithArg2": 99
    }));
}