async-graphql/src/scalars/any.rs
Koxiaet 47259548c4 Support service parsing in async-graphql-parser
- Instead of adding a separate module `schema` like there was before,
since service parsing and executable parsing have a fair amount of
overlap I put them as two submodules `executable` and `service` in both
`parse` and `types`. Also, the grammar is unified under one `.pest`
file.
- Added const equivalents to `Value`, `Directive` etc
- Change the reexport `async_graphql::Value` from
`async_graphql_parser::types::Value` to
`async_graphql_parser::types::ConstValue` since in 99% of cases in this library
a const value is wanted instead of a value.
- Added consistent usage of executable/service instead of the ambiguous
query/schema.
- Some of the tests actually had invalid GraphQL so the new more correct
grammar made them fail, that was fixed.
- Added a `Name` newtype to refer to GraphQL names
(`[A-Za-z_][A-Za-z_0-9]*`) since they are used so frequently.
2020-09-08 09:21:27 +01:00

56 lines
1.4 KiB
Rust

use crate::{InputValueResult, ScalarType, Value};
use async_graphql_derive::Scalar;
use serde::de::DeserializeOwned;
/// 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))
}
fn is_valid(_value: &Value) -> bool {
true
}
fn to_value(&self) -> Value {
self.0.clone()
}
}
impl Any {
/// Parse this `Any` value to T by `serde_json`.
pub fn parse_value<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
serde_json::from_value(self.to_value().into_json()?)
}
}
impl<T: Into<Value>> From<T> for Any {
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);
}
}