2020-09-14 08:17:53 +00:00
|
|
|
use crate::parser::types::Name;
|
|
|
|
use crate::{
|
2020-09-18 00:52:13 +00:00
|
|
|
InputValueError, InputValueResult, InputValueType, OutputValueType, Scalar, ScalarType, Value,
|
2020-09-14 08:17:53 +00:00
|
|
|
};
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
|
|
|
|
/// A scalar that can represent any JSON Object value.
|
2020-09-18 00:52:13 +00:00
|
|
|
#[Scalar(internal, name = "JSONObject")]
|
2020-09-14 08:17:53 +00:00
|
|
|
impl<T> ScalarType for BTreeMap<String, T>
|
|
|
|
where
|
|
|
|
T: OutputValueType + InputValueType + Send + Sync,
|
|
|
|
{
|
|
|
|
fn parse(value: Value) -> InputValueResult<Self> {
|
|
|
|
match value {
|
|
|
|
Value::Object(map) => {
|
|
|
|
let mut result = BTreeMap::new();
|
|
|
|
for (name, value) in map {
|
|
|
|
result.insert(name.to_string(), T::parse(Some(value))?);
|
|
|
|
}
|
|
|
|
Ok(result)
|
|
|
|
}
|
|
|
|
_ => Err(InputValueError::ExpectedType(value)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn to_value(&self) -> Value {
|
|
|
|
let mut map = BTreeMap::new();
|
|
|
|
for (name, value) in self {
|
|
|
|
if let Ok(name) = Name::new(name.clone()) {
|
|
|
|
map.insert(name, value.to_value());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Value::Object(map)
|
|
|
|
}
|
|
|
|
}
|