async-graphql/src/scalars/any.rs

59 lines
1.4 KiB
Rust
Raw Normal View History

use crate::{InputValueResult, ScalarType, Value};
use async_graphql_derive::Scalar;
2020-05-07 10:49:09 +00:00
use serde::de::DeserializeOwned;
2020-04-09 14:03:09 +00:00
/// Any scalar
///
/// The `Any` scalar is used to pass representations of entities from external services into the root `_entities` field for execution.
#[derive(Clone, PartialEq, Debug)]
pub struct Any(pub Value);
/// The `_Any` scalar is used to pass representations of entities from external services into the root `_entities` field for execution.
#[Scalar(internal, name = "_Any")]
impl ScalarType for Any {
fn parse(value: Value) -> InputValueResult<Self> {
Ok(Self(value))
2020-04-09 14:03:09 +00:00
}
fn is_valid(_value: &Value) -> bool {
true
}
fn to_value(&self) -> Value {
self.0.clone()
2020-04-09 14:03:09 +00:00
}
}
2020-05-07 10:49:09 +00:00
impl Any {
/// Parse this `Any` value to T by `serde_json`.
2020-05-07 10:50:47 +00:00
pub fn parse_value<T: DeserializeOwned>(&self) -> std::result::Result<T, serde_json::Error> {
serde_json::from_value(self.to_value().into())
2020-05-07 10:49:09 +00:00
}
}
impl<T> From<T> for Any
where
T: Into<Value>,
{
fn from(value: T) -> Any {
Any(value.into())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_conversion_ok() {
let value = Value::List(vec![
Value::Number(1.into()),
Value::Boolean(true),
Value::Null,
]);
let expected = Any(value.clone());
let output: Any = value.into();
assert_eq!(output, expected);
}
}