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

38 lines
1.0 KiB
Markdown
Raw Normal View History

2020-04-15 03:15:30 +00:00
# Custom scalars
2020-05-09 22:37:31 +00:00
In `Async-GraphQL` most common scalar types are built in, but you can also create your own scalar types.
Using `async-graphql::Scalar`, you can add support for a scalar when you implement it. You only need to implement parsing and output functions.
The following example defines a 64-bit integer scalar where its input and output are strings. (Note: `Async-graphQL` already supports 64-bit integers and uses strings as input and output.)
```rust
use async_graphql::*;
struct StringNumber(i64);
#[Scalar]
impl ScalarType for StringNumber {
fn type_name() -> &'static str {
// Name of type
"StringNumber"
}
fn parse(value: &Value) -> Option<Self> {
if let Value::String(value) = value {
// Parse the integer value
value.parse().ok().map(StringNumber)
} else {
// If the type does not match, return None
None
}
}
fn to_json(&self) -> Result<serde_json::Value> {
Ok(serde_json::to_value(self.0).unwrap())
}
}
```