async-graphql/src/resolver_utils/scalar.rs

162 lines
4.7 KiB
Rust
Raw Normal View History

2020-09-23 19:23:15 +00:00
use crate::{InputValueResult, Value};
/// A GraphQL scalar.
///
/// You can implement the trait to create a custom scalar.
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// struct MyInt(i32);
///
/// #[Scalar]
/// impl ScalarType for MyInt {
/// fn parse(value: Value) -> InputValueResult<Self> {
/// if let Value::Number(n) = &value {
/// if let Some(n) = n.as_i64() {
/// return Ok(MyInt(n as i32));
/// }
/// }
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
/// Err(InputValueError::expected_type(value))
/// }
///
/// fn to_value(&self) -> Value {
/// Value::Number(self.0.into())
/// }
/// }
/// ```
pub trait ScalarType: Sized + Send {
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
/// Parse a scalar value.
fn parse(value: Value) -> InputValueResult<Self>;
/// Checks for a valid scalar value.
///
/// Implementing this function can find incorrect input values during the verification phase, which can improve performance.
fn is_valid(_value: &Value) -> bool {
true
}
/// Convert the scalar to `Value`.
fn to_value(&self) -> Value;
}
2020-10-12 12:40:55 +00:00
/// Define a scalar
///
/// If your type implemented `serde::Serialize` and `serde::Deserialize`, then you can use this macro to define a scalar more simply.
/// It helps you implement the `ScalarType::parse` and `ScalarType::to_value` functions by calling the [from_value](fn.from_value.html) and [to_value](fn.to_value.html) functions.
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
/// use serde::{Serialize, Deserialize};
/// use std::collections::HashMap;
///
/// #[derive(Serialize, Deserialize)]
/// struct MyValue {
/// a: i32,
/// b: HashMap<String, i32>,
/// }
///
/// scalar!(MyValue);
///
/// // Rename to `MV`.
/// // scalar!(MyValue, "MV");
///
/// // Rename to `MV` and add description.
/// // scalar!(MyValue, "MV", "This is my value");
///
/// struct Query;
///
/// #[Object]
/// impl Query {
/// async fn value(&self, input: MyValue) -> MyValue {
/// input
/// }
/// }
///
/// async_std::task::block_on(async move {
/// let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
/// let res = schema.execute(r#"{ value(input: {a: 10, b: {v1: 1, v2: 2} }) }"#).await.into_result().unwrap().data;
/// assert_eq!(res, value!({
/// "value": {
/// "a": 10,
/// "b": {"v1": 1, "v2": 2},
/// }
/// }));
/// });
///
///
/// ```
#[macro_export]
macro_rules! scalar {
2020-11-03 05:50:22 +00:00
($ty:ty, $name:literal, $desc:literal) => {
$crate::scalar_internal!($ty, $name, ::std::option::Option::Some($desc));
2020-10-12 12:40:55 +00:00
};
2020-11-03 05:50:22 +00:00
($ty:ty, $name:literal) => {
$crate::scalar_internal!($ty, $name, ::std::option::Option::None);
2020-10-12 12:40:55 +00:00
};
($ty:ty) => {
2020-10-16 10:37:59 +00:00
$crate::scalar_internal!($ty, ::std::stringify!($ty), ::std::option::Option::None);
2020-10-12 12:40:55 +00:00
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! scalar_internal {
($ty:ty, $name:expr, $desc:expr) => {
impl $crate::Type for $ty {
2020-10-16 10:37:59 +00:00
fn type_name() -> ::std::borrow::Cow<'static, ::std::primitive::str> {
2020-10-12 12:40:55 +00:00
::std::borrow::Cow::Borrowed($name)
}
2020-10-16 10:37:59 +00:00
fn create_type_info(
registry: &mut $crate::registry::Registry,
) -> ::std::string::String {
2020-10-12 12:40:55 +00:00
registry.create_type::<$ty, _>(|_| $crate::registry::MetaType::Scalar {
2020-10-16 19:21:46 +00:00
name: ::std::borrow::ToOwned::to_owned($name),
2020-10-12 12:40:55 +00:00
description: $desc,
is_valid: |value| <$ty as $crate::ScalarType>::is_valid(value),
})
}
}
impl $crate::ScalarType for $ty {
fn parse(value: $crate::Value) -> $crate::InputValueResult<Self> {
2020-10-16 10:37:59 +00:00
::std::result::Result::Ok($crate::from_value(value)?)
2020-10-12 12:40:55 +00:00
}
fn to_value(&self) -> $crate::Value {
$crate::to_value(self).unwrap_or_else(|_| $crate::Value::Null)
}
}
impl $crate::InputType for $ty {
2020-10-16 10:37:59 +00:00
fn parse(
value: ::std::option::Option<$crate::Value>,
) -> $crate::InputValueResult<Self> {
2020-10-12 12:40:55 +00:00
<$ty as $crate::ScalarType>::parse(value.unwrap_or_default())
}
fn to_value(&self) -> $crate::Value {
<$ty as $crate::ScalarType>::to_value(self)
}
}
#[$crate::async_trait::async_trait]
impl $crate::OutputType for $ty {
2020-10-12 12:40:55 +00:00
async fn resolve(
&self,
_: &$crate::ContextSelectionSet<'_>,
_field: &$crate::Positioned<$crate::parser::types::Field>,
) -> $crate::ServerResult<$crate::Value> {
2020-10-16 10:37:59 +00:00
::std::result::Result::Ok($crate::ScalarType::to_value(self))
2020-10-12 12:40:55 +00:00
}
}
};
}