Merge pull request #236 from D1plo1d/merged-object-docs

Add GQLMergedObject to docs
This commit is contained in:
Sunli 2020-08-11 11:35:21 +08:00 committed by GitHub
commit adea9ae2ff
3 changed files with 49 additions and 20 deletions

View File

@ -7,6 +7,7 @@
- [Object](define_complex_object.md)
- [Context](context.md)
- [Error handling](error_handling.md)
- [Merging Objects](merging_objects.md)
- [Enum](define_enum.md)
- [Interface](define_interface.md)
- [Union](define_union.md)

View File

@ -33,23 +33,3 @@ impl MyObject {
}
}
```
## Implement Object multiple times for the same type
Usually we can create multiple implementations for the same type in Rust, but due to the limitation of procedural macros, we can not create multiple Object implementations for the same type. For example, the following code will fail to compile.
```rust
#[Object]
impl MyObject {
async fn field1(&self) -> i32 {
todo!()
}
}
#[Object]
impl MyObject {
async fn field2(&self) -> i32 {
todo!()
}
}
```

View File

@ -0,0 +1,48 @@
# Merging Objects
Usually we can create multiple implementations for the same type in Rust, but due to the limitation of procedural macros, we can not create multiple Object implementations for the same type. For example, the following code will fail to compile.
```rust
#[Object]
impl Query {
async fn users(&self) -> Vec<User> {
todo!()
}
}
#[Object]
impl Query {
async fn movies(&self) -> Vec<Movie> {
todo!()
}
}
```
Instead, the `#[derive(GQLMergedObject)]` macro allows you to split an object's resolvers across multiple file by merging 2 or more `#[Object]` implementations into one.
**Tip:** Every `#[Object]` needs a unique name even in a GQLMergedObject so make sure to give each object your merging it's own name.
```rust
#[Object]
impl UserQuery {
async fn users(&self) -> Vec<User> {
todo!()
}
}
#[Object]
impl MovieQuery {
async fn movies(&self) -> Vec<Movie> {
todo!()
}
}
#[derive(GQLMergedObject, Default)]
struct Query(UserQuery, MovieQuery);
let schema = Schema::new(
Query::default(),
EmptyMutation,
EmptySubscription
);
```