async-graphql/src/types/optional.rs

77 lines
2.0 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-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
}
impl<T: GQLInputValue> GQLInputValue for Option<T> {
2020-03-04 02:38:07 +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
}
}
}
#[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
}
2020-03-05 06:23:55 +00:00
2020-03-05 13:34:31 +00:00
impl<T: GQLType> GQLType for &Option<T> {
fn type_name() -> Cow<'static, str> {
T::type_name()
}
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-05 13:34:31 +00:00
}
}
#[async_trait::async_trait]
impl<T: GQLOutputValue + Sync> GQLOutputValue for &Option<T> {
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> where {
if let Some(inner) = self {
inner.resolve(ctx).await
} else {
Ok(serde_json::Value::Null)
}
}
}
2020-03-05 06:23:55 +00:00
#[cfg(test)]
mod tests {
use crate::GQLType;
#[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
}
}