async-graphql/docs/en/src/procedural_macros.md

50 lines
1.2 KiB
Markdown
Raw Normal View History

2020-08-28 06:04:59 +00:00
# Two ways to define types
2020-09-01 05:47:22 +00:00
I think you have discovered that GraphQL types can be defined using both an attribute macro and a derive.
2020-08-28 06:04:59 +00:00
The following is the corresponding table:
|Type|Attribute macro|Derive|
|---|-----|----|
|Enum|Enum|GQLEnum|
|Simple Object|SimpleObject|GQLSimpleObject|
|Input Object|InputObject|GQLInputObject|
|Interface|Interface|GQLInterface|
|Union|Union|GQLUnion|
|Merged Object|MergedObject|GQLMergedObject|
|Merged Subscription|MergedSubscription|GQLMergedSubscription|
2020-09-01 05:47:22 +00:00
The advantage of the attribute macro is that you can provide parameters at the same time, for example
2020-08-28 06:04:59 +00:00
```rust
#[SimpleObject(name = "ABC")]
struct MyObject {
value: i32,
}
```
2020-09-01 05:47:22 +00:00
**However, attribute macros do not support conditional compilation**. The following does not work:
2020-08-28 06:04:59 +00:00
```rust
#[SimpleObject]
struct MyObject {
#[cfg(windows)]
value: i32,
#[cfg(not(windows))]
value: i32,
}
```
2020-09-01 05:47:22 +00:00
Deriving, on the other hand, does support conditional compilation, but as derive macros can't take parameters you need to provide them separately. For example:
2020-08-28 06:04:59 +00:00
```rust
#[derive(SimpleObject)]
#[graphql(name = "ABC")]
struct MyObject {
value: i32,
}
```
2020-09-01 05:47:22 +00:00
_Which way you use to define types is up to you, personally I prefer to use derive._