async-graphql/src/base.rs

122 lines
3.2 KiB
Rust
Raw Normal View History

use std::borrow::Cow;
2020-09-06 06:16:36 +00:00
use crate::parser::types::Field;
2020-03-19 09:20:12 +00:00
use crate::registry::Registry;
use crate::{
registry, ContainerType, ContextSelectionSet, InputValueResult, Positioned, Result,
ServerResult, Value,
};
2020-03-01 10:54:34 +00:00
#[doc(hidden)]
pub trait Description {
fn description() -> &'static str;
}
2020-10-13 02:19:30 +00:00
/// Represents a GraphQL type.
2020-03-20 03:56:08 +00:00
///
/// All GraphQL types implement this trait, such as `Scalar`, `Object`, `Union` ...
2020-03-19 09:20:12 +00:00
pub trait Type {
2020-03-09 10:05:52 +00:00
/// Type the name.
2020-03-03 03:48:00 +00:00
fn type_name() -> Cow<'static, str>;
2020-03-09 10:05:52 +00:00
/// Qualified typename.
2020-03-03 11:15:18 +00:00
fn qualified_type_name() -> String {
format!("{}!", Self::type_name())
}
/// Introspection type name
///
2020-04-03 01:31:58 +00:00
/// Is the return value of field `__typename`, the interface and union should return the current type, and the others return `Type::type_name`.
fn introspection_type_name(&self) -> Cow<'static, str> {
Self::type_name()
}
2020-03-09 10:05:52 +00:00
/// Create type information in the registry and return qualified typename.
2020-03-03 11:15:18 +00:00
fn create_type_info(registry: &mut registry::Registry) -> String;
2020-03-03 03:48:00 +00:00
}
2020-10-13 02:19:30 +00:00
/// Represents a GraphQL input value.
pub trait InputType: Type + Sized {
2020-09-06 05:38:31 +00:00
/// Parse from `Value`. None represents undefined.
fn parse(value: Option<Value>) -> InputValueResult<Self>;
2020-09-06 05:38:31 +00:00
/// Convert to a `Value` for introspection.
fn to_value(&self) -> Value;
2020-03-03 03:48:00 +00:00
}
2020-10-13 02:19:30 +00:00
/// Represents a GraphQL output value.
2020-03-03 03:48:00 +00:00
#[async_trait::async_trait]
pub trait OutputType: Type {
2020-10-10 02:32:43 +00:00
/// Resolve an output value to `async_graphql::Value`.
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
2020-10-10 02:32:43 +00:00
) -> ServerResult<Value>;
2020-03-03 03:48:00 +00:00
}
impl<T: Type + Send + Sync + ?Sized> Type for &T {
2020-03-19 09:20:12 +00:00
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn create_type_info(registry: &mut Registry) -> String {
T::create_type_info(registry)
}
}
2020-03-01 10:54:34 +00:00
#[async_trait::async_trait]
impl<T: OutputType + Send + Sync + ?Sized> OutputType for &T {
2020-03-21 01:32:13 +00:00
#[allow(clippy::trivially_copy_pass_by_ref)]
2020-05-20 00:18:28 +00:00
async fn resolve(
&self,
ctx: &ContextSelectionSet<'_>,
field: &Positioned<Field>,
2020-10-10 02:32:43 +00:00
) -> ServerResult<Value> {
2020-05-20 00:18:28 +00:00
T::resolve(*self, ctx, field).await
2020-03-01 10:54:34 +00:00
}
}
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
impl<T: Type> Type for Result<T> {
2020-05-03 14:32:37 +00:00
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn qualified_type_name() -> String {
T::qualified_type_name()
}
fn create_type_info(registry: &mut registry::Registry) -> String {
2020-05-03 15:00:20 +00:00
T::create_type_info(registry)
2020-05-03 14:32:37 +00:00
}
}
#[async_trait::async_trait]
impl<T: OutputType + Sync> OutputType for Result<T> {
2020-05-03 14:32:37 +00:00
async fn resolve(
&self,
2020-05-03 14:32:37 +00:00
ctx: &ContextSelectionSet<'_>,
2020-05-20 00:18:28 +00:00
field: &Positioned<Field>,
2020-10-10 02:32:43 +00:00
) -> ServerResult<Value> {
match self {
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
Ok(value) => Ok(value.resolve(ctx, field).await?),
Err(err) => Err(err.clone().into_server_error().at(field.pos)),
2020-05-03 14:32:37 +00:00
}
}
}
2020-09-29 23:45:48 +00:00
/// A GraphQL object.
pub trait ObjectType: ContainerType {}
#[async_trait::async_trait]
impl<T: ObjectType + Send + Sync> ObjectType for &T {}
/// A GraphQL interface.
pub trait InterfaceType: ContainerType {}
/// A GraphQL interface.
pub trait UnionType: ContainerType {}
/// A GraphQL input object.
pub trait InputObjectType: InputType {}