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

63 lines
1.2 KiB
Markdown
Raw Normal View History

2020-05-26 15:27:50 +00:00
# Default value
You can define default values for input value types.
2020-09-01 05:47:22 +00:00
Below are some examples.
2020-05-26 15:27:50 +00:00
## Object field
```rust
use async_graphql::*;
struct Query;
fn my_default() -> i32 {
30
}
#[Object]
2020-05-26 15:27:50 +00:00
impl Query {
// The default value of the value parameter is 0, it will call i32::default()
2020-09-28 09:44:00 +00:00
fn test1(&self, #[graphql(default)] value: i32) {}
2020-05-26 15:27:50 +00:00
// The default value of the value parameter is 10
2020-09-28 09:44:00 +00:00
fn test2(&self, #[graphql(default = 10)] value: i32) {}
2020-05-26 15:27:50 +00:00
// The default value of the value parameter uses the return result of the my_default function, the value is 30.
2020-09-28 09:44:00 +00:00
fn test3(&self, #[graphql(default_with = "my_default()")] value: i32) {}
2020-05-26 15:27:50 +00:00
}
```
## Interface field
```rust
use async_graphql::*;
#[derive(Interface)]
2020-09-13 04:12:32 +00:00
#[graphql(
2020-05-26 15:27:50 +00:00
field(name = "test1", arg(name = "value", default)),
field(name = "test2", arg(name = "value", default = 10)),
field(name = "test3", arg(name = "value", default_with = "my_default()")),
2020-05-26 15:27:50 +00:00
)]
enum MyInterface {
MyObj(MyObj),
}
```
## Input object field
```rust
use async_graphql::*;
#[derive(InputObject)]
2020-05-26 15:27:50 +00:00
struct MyInputObject {
2020-09-28 09:44:00 +00:00
#[graphql(default)]
2020-05-26 15:27:50 +00:00
value1: i32,
2020-09-28 09:44:00 +00:00
#[graphql(default = 10)]
2020-05-26 15:27:50 +00:00
value2: i32,
#[graphql(default_with = "my_default()")]
2020-05-26 15:27:50 +00:00
value3: i32,
}
2020-09-01 05:47:22 +00:00
```