2020-04-15 03:15:30 +00:00
|
|
|
# Interface
|
2020-05-09 17:53:41 +00:00
|
|
|
|
2020-05-11 04:39:43 +00:00
|
|
|
`Interface` is used to abstract `Object`s with common fields.
|
|
|
|
`Async-graphql` implemented it as a wrapper.
|
|
|
|
The wrapper will forward Resolve to the `Object` that implemented this `Interface`.
|
2020-05-09 17:53:41 +00:00
|
|
|
Therefore, the `Object`'s fields' type, arguments must match with the `Interface`'s.
|
|
|
|
|
|
|
|
`Async-graphql` implemented auto conversion from `Object` to `Interface`, you only need to call `Into::into`.
|
|
|
|
|
2020-05-28 15:50:01 +00:00
|
|
|
Interface fields names transforms to camelCase in schema definition.
|
|
|
|
If you need e.g. snake_cased field name, there is `method` argument in field.
|
|
|
|
|
|
|
|
- When the `name` and `method` exist together, the `name` is the graphql name and the `method` is the rust method name.
|
|
|
|
- When only `name` exists, `name.to_camel_case()` is the graphql name and the `name` is the rust method name.
|
|
|
|
|
2020-05-09 17:53:41 +00:00
|
|
|
```rust
|
|
|
|
use async_graphql::*;
|
|
|
|
|
|
|
|
struct Circle {
|
|
|
|
radius: f32,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[Object]
|
|
|
|
impl Circle {
|
|
|
|
async fn area(&self) -> f32 {
|
|
|
|
std::f32::consts::PI * self.radius * self.radius
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn scale(&self, s: f32) -> Shape {
|
|
|
|
Circle { radius: self.radius * s }.into()
|
|
|
|
}
|
2020-05-28 15:50:01 +00:00
|
|
|
|
|
|
|
#[field(name = "short_description")]
|
|
|
|
async fn short_description(&self) -> String {
|
|
|
|
"Circle".to_string()
|
|
|
|
}
|
2020-05-09 17:53:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
struct Square {
|
|
|
|
width: f32,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[Object]
|
|
|
|
impl Square {
|
|
|
|
async fn area(&self) -> f32 {
|
|
|
|
self.width * self.width
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn scale(&self, s: f32) -> Shape {
|
|
|
|
Square { width: self.width * s }.into()
|
|
|
|
}
|
2020-05-28 15:50:01 +00:00
|
|
|
|
|
|
|
#[field(name = "short_description")]
|
|
|
|
async fn short_description(&self) -> String {
|
|
|
|
"Square".to_string()
|
|
|
|
}
|
2020-05-09 17:53:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[Interface(
|
|
|
|
field(name = "area", type = "f32"),
|
|
|
|
field(name = "scale", type = "Shape", arg(name = "s", type = "f32"))
|
2020-05-28 15:50:01 +00:00
|
|
|
field(name = "short_description", method = "short_description", type = "String")
|
2020-05-09 17:53:41 +00:00
|
|
|
)]
|
2020-05-11 04:39:43 +00:00
|
|
|
enum Shape {
|
|
|
|
Circle(Circle),
|
|
|
|
Square(Square),
|
|
|
|
}
|
|
|
|
```
|