2020-04-16 02:22:57 +00:00
|
|
|
|
# 简单对象(SimpleObject)
|
|
|
|
|
|
2020-05-13 04:49:43 +00:00
|
|
|
|
简单对象是把Rust结构的所有字段都直接映射到GraphQL对象,不支持定义单独的Resolver函数。
|
2020-04-16 02:22:57 +00:00
|
|
|
|
|
2020-09-28 09:44:00 +00:00
|
|
|
|
下面的例子定义了一个名称为MyObject的对象,包含字段`a`和`b`,`c`由于标记为`#[graphql(skip)]`,所以不会映射到GraphQL。
|
2020-04-16 02:22:57 +00:00
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
use async_graphql::*;
|
|
|
|
|
|
2020-09-18 00:52:13 +00:00
|
|
|
|
#[derive(SimpleObject)]
|
2020-04-16 02:22:57 +00:00
|
|
|
|
struct MyObject {
|
2020-05-10 04:41:05 +00:00
|
|
|
|
/// Value a
|
2020-04-16 02:22:57 +00:00
|
|
|
|
a: i32,
|
2020-05-10 04:41:05 +00:00
|
|
|
|
|
2020-09-28 09:44:00 +00:00
|
|
|
|
/// Value b
|
2020-04-16 02:22:57 +00:00
|
|
|
|
b: i32,
|
|
|
|
|
|
2020-09-28 09:44:00 +00:00
|
|
|
|
#[graphql(skip)]
|
2020-04-16 02:22:57 +00:00
|
|
|
|
c: i32,
|
|
|
|
|
}
|
|
|
|
|
```
|
2021-01-16 00:08:36 +00:00
|
|
|
|
|
|
|
|
|
## 泛型
|
|
|
|
|
|
|
|
|
|
如果你希望其它类型能够重用`SimpleObject`,则可以定义泛型的`SimpleObject`,并指定具体的类型。
|
|
|
|
|
|
|
|
|
|
在下面的示例中,创建了两种`SimpleObject`类型:
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
#[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如下:
|
|
|
|
|
|
|
|
|
|
```gql
|
|
|
|
|
type SomeName {
|
|
|
|
|
field1: SomeType
|
|
|
|
|
field2: String!
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SomeOtherName {
|
|
|
|
|
field1: SomeOtherType
|
|
|
|
|
field2: String!
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
在其它`Object`中使用具体的泛型类型:
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
#[derive(SimpleObject)]
|
|
|
|
|
pub struct YetAnotherObject {
|
|
|
|
|
a: SomeGenericObject<SomeType>,
|
|
|
|
|
b: SomeGenericObject<SomeOtherType>,
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
你可以将多个通用类型传递给`params()`,并用逗号分隔。
|
2021-03-17 12:51:30 +00:00
|
|
|
|
|
|
|
|
|
## 复杂字段
|
|
|
|
|
|
|
|
|
|
有时GraphQL对象的大多数字段仅返回结构成员的值,但是少数字段需要计算。 通常我们使用`Object`宏来定义这样一个GraphQL对象。
|
|
|
|
|
|
|
|
|
|
用`ComplexObject`宏可以更漂亮的完成这件事,我们可以使用`SimpleObject`宏来定义
|
|
|
|
|
一些简单的字段,并使用`ComplexObject`宏来定义其他一些需要计算的字段。
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
#[derive(SimpleObject)]
|
|
|
|
|
#[graphql(complex)] // 注意: 如果你希望ComplexObject宏生效,complex属性是必须的
|
|
|
|
|
struct MyObj {
|
|
|
|
|
a: i32,
|
|
|
|
|
b: i32,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[ComplexObject]
|
|
|
|
|
impl MyObj {
|
|
|
|
|
async fn c(&self) -> i32 {
|
|
|
|
|
self.a + self.b
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|