async-graphql/src/types/external/optional.rs

66 lines
1.7 KiB
Rust
Raw Normal View History

2020-09-06 06:16:36 +00:00
use crate::parser::types::Field;
use crate::{
2020-05-20 00:18:28 +00:00
registry, ContextSelectionSet, InputValueResult, InputValueType, OutputValueType, Positioned,
Result, Type, Value,
};
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
2020-03-19 09:20:12 +00:00
impl<T: Type> Type for Option<T> {
2020-03-02 00:24:49 +00:00
fn type_name() -> Cow<'static, str> {
2020-03-03 11:15:18 +00:00
T::type_name()
2020-03-02 00:24:49 +00:00
}
2020-03-03 03:48:00 +00:00
2020-03-03 11:15:18 +00:00
fn qualified_type_name() -> String {
T::type_name().to_string()
}
fn create_type_info(registry: &mut registry::Registry) -> String {
2020-03-06 00:42:06 +00:00
T::create_type_info(registry);
T::type_name().to_string()
2020-03-03 03:48:00 +00:00
}
2020-03-02 00:24:49 +00:00
}
2020-03-19 09:20:12 +00:00
impl<T: InputValueType> InputValueType for Option<T> {
fn parse(value: Option<Value>) -> InputValueResult<Self> {
match value.unwrap_or_default() {
Value::Null => Ok(None),
value => Ok(Some(T::parse(Some(value))?)),
2020-03-02 00:24:49 +00:00
}
}
fn to_value(&self) -> Value {
match self {
Some(value) => value.to_value(),
None => Value::Null,
}
}
2020-03-02 00:24:49 +00:00
}
#[async_trait::async_trait]
2020-03-19 09:20:12 +00:00
impl<T: OutputValueType + Sync> OutputValueType for Option<T> {
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
) -> Result<serde_json::Value> where {
if let Some(inner) = self {
2020-05-20 00:18:28 +00:00
OutputValueType::resolve(inner, ctx, field).await
2020-03-05 13:34:31 +00:00
} else {
2020-03-25 03:39:28 +00:00
Ok(serde_json::Value::Null)
2020-03-05 13:34:31 +00:00
}
}
}
2020-03-05 06:23:55 +00:00
#[cfg(test)]
mod tests {
2020-03-19 09:20:12 +00:00
use crate::Type;
2020-03-05 06:23:55 +00:00
#[test]
fn test_optional_type() {
assert_eq!(Option::<i32>::type_name(), "Int");
assert_eq!(Option::<i32>::qualified_type_name(), "Int");
2020-03-06 00:42:06 +00:00
assert_eq!(&Option::<i32>::type_name(), "Int");
assert_eq!(&Option::<i32>::qualified_type_name(), "Int");
2020-03-05 06:23:55 +00:00
}
}