async-graphql/src/types/optional.rs

44 lines
1.2 KiB
Rust
Raw Normal View History

2020-03-03 11:15:18 +00:00
use crate::{registry, ContextSelectionSet, GQLInputValue, GQLOutputValue, GQLType, Result, Value};
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
impl<T: GQLType> GQLType for Option<T> {
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-03 03:48:00 +00:00
T::create_type_info(registry)
}
2020-03-02 00:24:49 +00:00
}
impl<T: GQLInputValue> GQLInputValue for Option<T> {
2020-03-03 11:15:18 +00:00
fn parse(value: Value) -> Option<Self> {
2020-03-02 00:24:49 +00:00
match value {
2020-03-03 11:15:18 +00:00
Value::Null => Some(None),
_ => Some(GQLInputValue::parse(value)?),
2020-03-02 00:24:49 +00:00
}
}
2020-03-03 11:15:18 +00:00
fn parse_from_json(value: serde_json::Value) -> Option<Self> {
2020-03-02 00:24:49 +00:00
match value {
2020-03-03 11:15:18 +00:00
serde_json::Value::Null => Some(None),
_ => Some(GQLInputValue::parse_from_json(value)?),
2020-03-02 00:24:49 +00:00
}
}
}
#[async_trait::async_trait]
2020-03-02 11:25:21 +00:00
impl<T: GQLOutputValue + Sync> GQLOutputValue for Option<T> {
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> where {
2020-03-02 00:24:49 +00:00
if let Some(inner) = self {
inner.resolve(ctx).await
} else {
Ok(serde_json::Value::Null)
}
}
2020-03-03 03:48:00 +00:00
}