2020-04-02 02:21:04 +00:00
|
|
|
use crate::{
|
2020-05-20 00:18:28 +00:00
|
|
|
registry, ContextSelectionSet, InputValueResult, InputValueType, OutputValueType, Positioned,
|
|
|
|
Result, Type, Value,
|
2020-04-02 02:21:04 +00:00
|
|
|
};
|
2020-05-20 00:18:28 +00:00
|
|
|
use async_graphql_parser::query::Field;
|
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> {
|
2020-05-28 07:00:55 +00:00
|
|
|
fn parse(value: Option<Value>) -> InputValueResult<Self> {
|
|
|
|
match value.unwrap_or_default() {
|
2020-05-10 10:27:46 +00:00
|
|
|
Value::Null => Ok(None),
|
2020-05-28 07:00:55 +00:00
|
|
|
value => Ok(Some(T::parse(Some(value))?)),
|
2020-03-02 00:24:49 +00:00
|
|
|
}
|
|
|
|
}
|
2020-05-26 10:34:43 +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 {
|
2020-05-05 13:06:48 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|