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.
183 lines
4.7 KiB
Rust
183 lines
4.7 KiB
Rust
use crate::parser::types::Field;
|
|
use crate::registry::{MetaType, Registry};
|
|
use crate::{
|
|
ContextSelectionSet, InputValueResult, OutputValueType, Positioned, Scalar, ScalarType,
|
|
ServerResult, Type, Value,
|
|
};
|
|
use serde::de::DeserializeOwned;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::borrow::Cow;
|
|
use std::ops::{Deref, DerefMut};
|
|
|
|
/// A scalar that can represent any JSON value.
|
|
///
|
|
/// If the inner type cannot be serialized as JSON (e.g. it has non-string keys) it will be `null`.
|
|
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Hash, Default)]
|
|
#[serde(transparent)]
|
|
pub struct Json<T>(pub T);
|
|
|
|
impl<T> Deref for Json<T> {
|
|
type Target = T;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl<T> DerefMut for Json<T> {
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
&mut self.0
|
|
}
|
|
}
|
|
|
|
impl<T: DeserializeOwned + Serialize> From<T> for Json<T> {
|
|
fn from(value: T) -> Self {
|
|
Self(value)
|
|
}
|
|
}
|
|
|
|
/// A scalar that can represent any JSON value.
|
|
#[Scalar(internal, name = "JSON")]
|
|
impl<T: DeserializeOwned + Serialize + Send + Sync> ScalarType for Json<T> {
|
|
fn parse(value: Value) -> InputValueResult<Self> {
|
|
Ok(serde_json::from_value(value.into_json()?)?)
|
|
}
|
|
|
|
fn to_value(&self) -> Value {
|
|
serde_json::to_value(&self.0)
|
|
.ok()
|
|
.and_then(|json| Value::from_json(json).ok())
|
|
.unwrap_or_else(|| Value::Null)
|
|
}
|
|
}
|
|
|
|
/// A `Json` type that only implements `OutputValueType`.
|
|
#[derive(Serialize, Clone, Debug, Eq, PartialEq, Hash, Default)]
|
|
pub struct OutputJson<T>(pub T);
|
|
|
|
impl<T> Deref for OutputJson<T> {
|
|
type Target = T;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl<T> DerefMut for OutputJson<T> {
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
&mut self.0
|
|
}
|
|
}
|
|
|
|
impl<T: Serialize> From<T> for OutputJson<T> {
|
|
fn from(value: T) -> Self {
|
|
Self(value)
|
|
}
|
|
}
|
|
|
|
impl<T> Type for OutputJson<T> {
|
|
fn type_name() -> Cow<'static, str> {
|
|
Cow::Borrowed("Json")
|
|
}
|
|
|
|
fn create_type_info(registry: &mut Registry) -> String {
|
|
registry.create_type::<OutputJson<T>, _>(|_| MetaType::Scalar {
|
|
name: Self::type_name().to_string(),
|
|
description: None,
|
|
is_valid: |_| true,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[async_trait::async_trait]
|
|
impl<T: Serialize + Send + Sync> OutputValueType for OutputJson<T> {
|
|
async fn resolve(
|
|
&self,
|
|
_ctx: &ContextSelectionSet<'_>,
|
|
_field: &Positioned<Field>,
|
|
) -> ServerResult<serde_json::Value> {
|
|
Ok(serde_json::to_value(&self.0).unwrap_or_else(|_| serde_json::Value::Null))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use crate::*;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashMap;
|
|
|
|
#[async_std::test]
|
|
async fn test_json_type() {
|
|
#[derive(Serialize, Deserialize)]
|
|
struct MyStruct {
|
|
a: i32,
|
|
b: i32,
|
|
c: HashMap<String, i32>,
|
|
}
|
|
|
|
struct Query;
|
|
|
|
#[Object(internal)]
|
|
impl Query {
|
|
async fn obj(&self, input: Json<MyStruct>) -> Json<MyStruct> {
|
|
input
|
|
}
|
|
}
|
|
|
|
let query = r#"{ obj(input: { a: 1, b: 2, c: { a: 11, b: 22 } } ) }"#;
|
|
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
|
|
assert_eq!(
|
|
schema.execute(query).await.into_result().unwrap().data,
|
|
serde_json::json!({
|
|
"obj": {
|
|
"a": 1,
|
|
"b": 2,
|
|
"c": { "a": 11, "b": 22 }
|
|
}
|
|
})
|
|
);
|
|
}
|
|
|
|
#[async_std::test]
|
|
async fn test_output_json_type() {
|
|
#[derive(Serialize)]
|
|
struct MyStruct {
|
|
a: i32,
|
|
b: i32,
|
|
c: HashMap<String, i32>,
|
|
}
|
|
|
|
struct Query;
|
|
|
|
#[Object(internal)]
|
|
impl Query {
|
|
async fn obj(&self) -> OutputJson<MyStruct> {
|
|
MyStruct {
|
|
a: 1,
|
|
b: 2,
|
|
c: {
|
|
let mut values = HashMap::new();
|
|
values.insert("a".to_string(), 11);
|
|
values.insert("b".to_string(), 22);
|
|
values
|
|
},
|
|
}
|
|
.into()
|
|
}
|
|
}
|
|
|
|
let query = r#"{ obj }"#;
|
|
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
|
|
assert_eq!(
|
|
schema.execute(query).await.into_result().unwrap().data,
|
|
serde_json::json!({
|
|
"obj": {
|
|
"a": 1,
|
|
"b": 2,
|
|
"c": { "a": 11, "b": 22 }
|
|
}
|
|
})
|
|
);
|
|
}
|
|
}
|