async-graphql/docs/zh-CN/src/define_simple_object.md
Edward Rudd 3b7ed74d11 correct doc examples so they compile
- examples to fix still
  - error_extensions.md ResultExt example does not compile!
     - trait ErrorExtensions is not implemented for ParseIntError
  - dataloader
     - requires sqlx to work. So we either "stub" it OR we rewrite them simpler to use a  simple "faux" db library
2022-06-02 17:32:12 -04:00

3.0 KiB
Raw Blame History

简单对象(SimpleObject)

简单对象是把Rust结构的所有字段都直接映射到GraphQL对象不支持定义单独的Resolver函数。

下面的例子定义了一个名称为MyObject的对象包含字段abc由于标记为#[graphql(skip)]所以不会映射到GraphQL。

# extern crate async_graphql;
use async_graphql::*;

#[derive(SimpleObject)]
struct MyObject {
    /// Value a
    a: i32,
    
    /// Value b
    b: i32,

    #[graphql(skip)]
    c: i32,
}

泛型

如果你希望其它类型能够重用SimpleObject,则可以定义泛型的SimpleObject,并指定具体的类型。

在下面的示例中,创建了两种SimpleObject类型:

# extern crate async_graphql;
# use async_graphql::*;
# #[derive(SimpleObject)]
# struct SomeType { a: i32 }
# #[derive(SimpleObject)]
# struct SomeOtherType { a: i32 }
#[derive(SimpleObject)]
#[graphql(concrete(name = "SomeName", params(SomeType)))]
#[graphql(concrete(name = "SomeOtherName", params(SomeOtherType)))]
pub struct SomeGenericObject<T: OutputType> {
    field1: Option<T>,
    field2: String
}

注意:每个泛型参数必须实现OutputType,如上所示。

生成的SDL如下:

type SomeName {
  field1: SomeType
  field2: String!
}

type SomeOtherName {
  field1: SomeOtherType
  field2: String!
}

在其它Object中使用具体的泛型类型:

# extern crate async_graphql;
# use async_graphql::*;
# #[derive(SimpleObject)]
# struct SomeType { a: i32 }
# #[derive(SimpleObject)]
# struct SomeOtherType { a: i32 }
# #[derive(SimpleObject)]
# #[graphql(concrete(name = "SomeName", params(SomeType)))]
# #[graphql(concrete(name = "SomeOtherName", params(SomeOtherType)))]
# pub struct SomeGenericObject<T: OutputType> {
#     field1: Option<T>,
#     field2: String,
# }
#[derive(SimpleObject)]
pub struct YetAnotherObject {
    a: SomeGenericObject<SomeType>,
    b: SomeGenericObject<SomeOtherType>,
}

你可以将多个通用类型传递给params,并用逗号分隔。

复杂字段

有时GraphQL对象的大多数字段仅返回结构成员的值但是少数字段需要计算。 通常我们使用Object宏来定义这样一个GraphQL对象。

ComplexObject宏可以更漂亮的完成这件事,我们可以使用SimpleObject宏来定义 一些简单的字段,并使用ComplexObject宏来定义其他一些需要计算的字段。

# extern crate async_graphql;
# use async_graphql::*;
#[derive(SimpleObject)]
#[graphql(complex)] // 注意: 如果你希望ComplexObject宏生效complex属性是必须的
struct MyObj {
    a: i32,
    b: i32,
}

#[ComplexObject]
impl MyObj {
    async fn c(&self) -> i32 {
        self.a + self.b     
    }
}

同时用于输入和输出

# extern crate async_graphql;
# use async_graphql::*;
#[derive(SimpleObject, InputObject)]
#[graphql(input_name = "MyObjInput")] // 注意: 你必须用input_name属性为输入类型定义一个新的名称否则将产生一个运行时错误。
struct MyObj {
    a: i32,
    b: i32,
}