2020-04-02 02:21:04 +00:00
|
|
|
use crate::{
|
|
|
|
registry, ContextSelectionSet, InputValueType, OutputValueType, Pos, 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> {
|
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),
|
2020-03-07 04:39:34 +00:00
|
|
|
_ => Some(Some(T::parse(value)?)),
|
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-04-02 02:21:04 +00:00
|
|
|
async fn resolve(
|
|
|
|
value: &Self,
|
|
|
|
ctx: &ContextSelectionSet<'_>,
|
|
|
|
pos: Pos,
|
|
|
|
) -> Result<serde_json::Value> where {
|
2020-03-06 15:58:43 +00:00
|
|
|
if let Some(inner) = value {
|
2020-04-02 02:21:04 +00:00
|
|
|
OutputValueType::resolve(inner, ctx, pos).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
|
|
|
}
|
|
|
|
}
|