async-graphql/src/types/maybe_undefined.rs

516 lines
14 KiB
Rust
Raw Normal View History

2022-04-19 04:25:11 +00:00
use std::{borrow::Cow, ops::Deref};
2020-10-15 06:38:10 +00:00
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{registry, InputType, InputValueError, InputValueResult, Value};
2020-10-15 06:38:10 +00:00
/// Similar to `Option`, but it has three states, `undefined`, `null` and `x`.
///
/// **Reference:** <https://spec.graphql.org/October2021/#sec-Null-Value>
2020-05-28 14:18:15 +00:00
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// struct Query;
///
/// #[Object]
2020-05-28 14:18:15 +00:00
/// impl Query {
/// async fn value1(&self, input: MaybeUndefined<i32>) -> i32 {
/// if input.is_null() {
/// 1
/// } else if input.is_undefined() {
/// 2
/// } else {
/// input.take().unwrap()
/// }
/// }
/// }
///
2021-11-20 03:16:48 +00:00
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
/// let query = r#"
/// {
/// v1:value1(input: 99)
/// v2:value1(input: null)
/// v3:value1
/// }"#;
/// assert_eq!(
/// schema.execute(query).await.into_result().unwrap().data,
/// value!({
/// "v1": 99,
/// "v2": 1,
/// "v3": 2,
/// })
/// );
/// # });
2020-05-28 14:18:15 +00:00
/// ```
#[allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum MaybeUndefined<T> {
Undefined,
Null,
Value(T),
}
impl<T> Default for MaybeUndefined<T> {
fn default() -> Self {
Self::Undefined
}
}
impl<T> MaybeUndefined<T> {
/// Returns true if the `MaybeUndefined<T>` is undefined.
#[inline]
pub const fn is_undefined(&self) -> bool {
2020-10-14 03:11:52 +00:00
matches!(self, MaybeUndefined::Undefined)
}
/// Returns true if the `MaybeUndefined<T>` is null.
#[inline]
pub const fn is_null(&self) -> bool {
2020-10-14 03:11:52 +00:00
matches!(self, MaybeUndefined::Null)
}
/// Returns true if the `MaybeUndefined<T>` contains value.
2020-09-17 03:22:09 +00:00
#[inline]
pub const fn is_value(&self) -> bool {
2020-10-14 03:11:52 +00:00
matches!(self, MaybeUndefined::Value(_))
2020-09-17 03:22:09 +00:00
}
2022-04-19 04:25:11 +00:00
/// Borrow the value, returns `None` if the the `MaybeUndefined<T>` is
/// `undefined` or `null`, otherwise returns `Some(T)`.
#[inline]
pub const fn value(&self) -> Option<&T> {
match self {
MaybeUndefined::Value(value) => Some(value),
_ => None,
}
}
/// Converts the `MaybeUndefined<T>` to `Option<T>`.
#[inline]
pub fn take(self) -> Option<T> {
match self {
MaybeUndefined::Value(value) => Some(value),
_ => None,
}
}
/// Converts the `MaybeUndefined<T>` to `Option<Option<T>>`.
#[inline]
pub const fn as_opt_ref(&self) -> Option<Option<&T>> {
match self {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(None),
MaybeUndefined::Value(value) => Some(Some(value)),
}
}
/// Converts the `MaybeUndefined<T>` to `Option<Option<&U>>`.
#[inline]
pub fn as_opt_deref<U>(&self) -> Option<Option<&U>>
where
U: ?Sized,
T: Deref<Target = U>,
{
match self {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(None),
MaybeUndefined::Value(value) => Some(Some(value.deref())),
}
}
/// Returns `true` if the `MaybeUndefined<T>` contains the given value.
#[inline]
pub fn contains_value<U>(&self, x: &U) -> bool
where
U: PartialEq<T>,
{
match self {
MaybeUndefined::Value(y) => x == y,
_ => false,
}
}
2022-04-19 04:25:11 +00:00
/// Returns `true` if the `MaybeUndefined<T>` contains the given nullable
/// value.
#[inline]
pub fn contains<U>(&self, x: &Option<U>) -> bool
where
U: PartialEq<T>,
{
match self {
MaybeUndefined::Value(y) => matches!(x, Some(v) if v == y),
MaybeUndefined::Null => matches!(x, None),
2021-11-04 13:05:36 +00:00
MaybeUndefined::Undefined => false,
}
}
2022-04-19 04:25:11 +00:00
/// Maps a `MaybeUndefined<T>` to `MaybeUndefined<U>` by applying a function
/// to the contained nullable value
#[inline]
pub fn map<U, F: FnOnce(Option<T>) -> Option<U>>(self, f: F) -> MaybeUndefined<U> {
match self {
2021-11-05 01:29:50 +00:00
MaybeUndefined::Value(v) => match f(Some(v)) {
Some(v) => MaybeUndefined::Value(v),
None => MaybeUndefined::Null,
},
2021-11-05 01:29:50 +00:00
MaybeUndefined::Null => match f(None) {
Some(v) => MaybeUndefined::Value(v),
None => MaybeUndefined::Null,
},
MaybeUndefined::Undefined => MaybeUndefined::Undefined,
}
}
2022-04-19 04:25:11 +00:00
/// Maps a `MaybeUndefined<T>` to `MaybeUndefined<U>` by applying a function
/// to the contained value
#[inline]
pub fn map_value<U, F: FnOnce(T) -> U>(self, f: F) -> MaybeUndefined<U> {
match self {
MaybeUndefined::Value(v) => MaybeUndefined::Value(f(v)),
MaybeUndefined::Null => MaybeUndefined::Null,
MaybeUndefined::Undefined => MaybeUndefined::Undefined,
}
}
/// Update `value` if the `MaybeUndefined<T>` is not undefined.
///
/// # Example
///
/// ```rust
/// use async_graphql::MaybeUndefined;
///
/// let mut value = None;
///
/// MaybeUndefined::Value(10i32).update_to(&mut value);
/// assert_eq!(value, Some(10));
///
/// MaybeUndefined::Undefined.update_to(&mut value);
/// assert_eq!(value, Some(10));
///
/// MaybeUndefined::Null.update_to(&mut value);
/// assert_eq!(value, None);
/// ```
pub fn update_to(self, value: &mut Option<T>) {
match self {
MaybeUndefined::Value(new) => *value = Some(new),
MaybeUndefined::Null => *value = None,
MaybeUndefined::Undefined => {}
};
}
}
impl<T: InputType> InputType for MaybeUndefined<T> {
type RawValueType = T::RawValueType;
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 {
T::create_type_info(registry);
T::type_name().to_string()
}
fn parse(value: Option<Value>) -> InputValueResult<Self> {
match value {
None => Ok(MaybeUndefined::Undefined),
Some(Value::Null) => Ok(MaybeUndefined::Null),
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
Some(value) => Ok(MaybeUndefined::Value(
2020-10-03 23:49:56 +00:00
T::parse(Some(value)).map_err(InputValueError::propagate)?,
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
)),
}
}
fn to_value(&self) -> Value {
match self {
MaybeUndefined::Value(value) => value.to_value(),
_ => Value::Null,
}
}
fn as_raw_value(&self) -> Option<&Self::RawValueType> {
if let MaybeUndefined::Value(value) = self {
value.as_raw_value()
} else {
None
}
}
}
impl<T, E> MaybeUndefined<Result<T, E>> {
2022-04-19 04:25:11 +00:00
/// Transposes a `MaybeUndefined` of a [`Result`] into a [`Result`] of a
/// `MaybeUndefined`.
///
2022-04-19 04:25:11 +00:00
/// [`MaybeUndefined::Undefined`] will be mapped to
/// [`Ok`]`(`[`MaybeUndefined::Undefined`]`)`. [`MaybeUndefined::Null`]
/// will be mapped to [`Ok`]`(`[`MaybeUndefined::Null`]`)`.
/// [`MaybeUndefined::Value`]`(`[`Ok`]`(_))` and
/// [`MaybeUndefined::Value`]`(`[`Err`]`(_))` will be mapped to
/// [`Ok`]`(`[`MaybeUndefined::Value`]`(_))` and [`Err`]`(_)`.
#[inline]
pub fn transpose(self) -> Result<MaybeUndefined<T>, E> {
match self {
MaybeUndefined::Undefined => Ok(MaybeUndefined::Undefined),
MaybeUndefined::Null => Ok(MaybeUndefined::Null),
MaybeUndefined::Value(Ok(v)) => Ok(MaybeUndefined::Value(v)),
2021-11-05 01:29:50 +00:00
MaybeUndefined::Value(Err(e)) => Err(e),
}
}
}
impl<T: Serialize> Serialize for MaybeUndefined<T> {
2020-10-15 06:38:10 +00:00
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
MaybeUndefined::Value(value) => value.serialize(serializer),
_ => serializer.serialize_none(),
}
}
}
impl<'de, T> Deserialize<'de> for MaybeUndefined<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<MaybeUndefined<T>, D::Error>
where
D: Deserializer<'de>,
{
Option::<T>::deserialize(deserializer).map(|value| match value {
Some(value) => MaybeUndefined::Value(value),
None => MaybeUndefined::Null,
})
}
}
impl<T> From<MaybeUndefined<T>> for Option<Option<T>> {
fn from(maybe_undefined: MaybeUndefined<T>) -> Self {
match maybe_undefined {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(None),
MaybeUndefined::Value(value) => Some(Some(value)),
}
}
}
impl<T> From<Option<Option<T>>> for MaybeUndefined<T> {
fn from(value: Option<Option<T>>) -> Self {
match value {
Some(Some(value)) => Self::Value(value),
Some(None) => Self::Null,
None => Self::Undefined,
}
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
2022-04-19 04:25:11 +00:00
use crate::*;
#[test]
fn test_maybe_undefined_type() {
assert_eq!(MaybeUndefined::<i32>::type_name(), "Int");
assert_eq!(MaybeUndefined::<i32>::qualified_type_name(), "Int");
assert_eq!(&MaybeUndefined::<i32>::type_name(), "Int");
assert_eq!(&MaybeUndefined::<i32>::qualified_type_name(), "Int");
}
#[test]
fn test_maybe_undefined_serde() {
assert_eq!(
to_value(&MaybeUndefined::Value(100i32)).unwrap(),
value!(100)
);
assert_eq!(
from_value::<MaybeUndefined<i32>>(value!(100)).unwrap(),
MaybeUndefined::Value(100)
);
assert_eq!(
from_value::<MaybeUndefined<i32>>(value!(null)).unwrap(),
MaybeUndefined::Null
);
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
struct A {
a: MaybeUndefined<i32>,
}
assert_eq!(
to_value(&A {
a: MaybeUndefined::Value(100i32)
})
.unwrap(),
value!({"a": 100})
);
assert_eq!(
to_value(&A {
a: MaybeUndefined::Null,
})
.unwrap(),
value!({ "a": null })
);
assert_eq!(
to_value(&A {
a: MaybeUndefined::Undefined,
})
.unwrap(),
value!({ "a": null })
);
assert_eq!(
from_value::<A>(value!({"a": 100})).unwrap(),
A {
a: MaybeUndefined::Value(100i32)
}
);
assert_eq!(
from_value::<A>(value!({ "a": null })).unwrap(),
A {
a: MaybeUndefined::Null
}
);
assert_eq!(
from_value::<A>(value!({})).unwrap(),
A {
a: MaybeUndefined::Null
}
);
}
#[test]
fn test_maybe_undefined_to_nested_option() {
assert_eq!(Option::<Option<i32>>::from(MaybeUndefined::Undefined), None);
assert_eq!(
Option::<Option<i32>>::from(MaybeUndefined::Null),
Some(None)
);
assert_eq!(
Option::<Option<i32>>::from(MaybeUndefined::Value(42)),
Some(Some(42))
);
}
#[test]
fn test_as_opt_ref() {
2022-04-20 06:21:23 +00:00
let value = MaybeUndefined::<String>::Undefined;
let r = value.as_opt_ref();
assert_eq!(r, None);
2022-04-20 06:21:23 +00:00
let value = MaybeUndefined::<String>::Null;
let r = value.as_opt_ref();
assert_eq!(r, Some(None));
2022-04-20 06:21:23 +00:00
let value = MaybeUndefined::<String>::Value("abc".to_string());
let r = value.as_opt_ref();
assert_eq!(r, Some(Some(&"abc".to_string())));
}
#[test]
fn test_as_opt_deref() {
2022-04-20 06:21:23 +00:00
let value = MaybeUndefined::<String>::Undefined;
let r = value.as_opt_deref();
assert_eq!(r, None);
2022-04-20 06:21:23 +00:00
let value = MaybeUndefined::<String>::Null;
let r = value.as_opt_deref();
assert_eq!(r, Some(None));
2022-04-20 06:21:23 +00:00
let value = MaybeUndefined::<String>::Value("abc".to_string());
let r = value.as_opt_deref();
assert_eq!(r, Some(Some("abc")));
}
#[test]
fn test_contains_value() {
let test = "abc";
let mut value: MaybeUndefined<String> = MaybeUndefined::Undefined;
assert!(!value.contains_value(&test));
value = MaybeUndefined::Null;
assert!(!value.contains_value(&test));
value = MaybeUndefined::Value("abc".to_string());
assert!(value.contains_value(&test));
}
#[test]
fn test_contains() {
let test = Some("abc");
let none: Option<&str> = None;
let mut value: MaybeUndefined<String> = MaybeUndefined::Undefined;
assert!(!value.contains(&test));
assert!(!value.contains(&none));
value = MaybeUndefined::Null;
assert!(!value.contains(&test));
assert!(value.contains(&none));
value = MaybeUndefined::Value("abc".to_string());
assert!(value.contains(&test));
assert!(!value.contains(&none));
}
#[test]
fn test_map_value() {
let mut value: MaybeUndefined<i32> = MaybeUndefined::Undefined;
assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Undefined);
value = MaybeUndefined::Null;
assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Null);
value = MaybeUndefined::Value(5);
assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Value(true));
}
#[test]
fn test_map() {
let mut value: MaybeUndefined<i32> = MaybeUndefined::Undefined;
assert_eq!(value.map(|v| Some(v.is_some())), MaybeUndefined::Undefined);
value = MaybeUndefined::Null;
2021-11-05 01:29:50 +00:00
assert_eq!(
value.map(|v| Some(v.is_some())),
MaybeUndefined::Value(false)
);
value = MaybeUndefined::Value(5);
2021-11-05 01:29:50 +00:00
assert_eq!(
value.map(|v| Some(v.is_some())),
MaybeUndefined::Value(true)
);
}
#[test]
fn test_transpose() {
let mut value: MaybeUndefined<Result<i32, &'static str>> = MaybeUndefined::Undefined;
assert_eq!(value.transpose(), Ok(MaybeUndefined::Undefined));
value = MaybeUndefined::Null;
assert_eq!(value.transpose(), Ok(MaybeUndefined::Null));
value = MaybeUndefined::Value(Ok(5));
assert_eq!(value.transpose(), Ok(MaybeUndefined::Value(5)));
2022-06-15 14:18:39 +00:00
value = MaybeUndefined::Value(Err("error"));
assert_eq!(value.transpose(), Err("error"));
}
}