async-graphql/derive/src/union.rs
Koxiaet 50009b66ce 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 20:06:44 +01:00

152 lines
5.7 KiB
Rust

use crate::args;
use crate::utils::{get_crate_name, get_rustdoc};
use proc_macro::TokenStream;
use quote::quote;
use std::collections::HashSet;
use syn::{Data, DeriveInput, Error, Fields, Result, Type};
pub fn generate(union_args: &args::Interface, input: &DeriveInput) -> Result<TokenStream> {
let crate_name = get_crate_name(union_args.internal);
let ident = &input.ident;
let generics = &input.generics;
let s = match &input.data {
Data::Enum(s) => s,
_ => {
return Err(Error::new_spanned(
input,
"Unions can only be applied to an enum.",
))
}
};
let mut enum_names = Vec::new();
let mut enum_items = HashSet::new();
let mut type_into_impls = Vec::new();
let gql_typename = union_args.name.clone().unwrap_or_else(|| ident.to_string());
let desc = union_args
.desc
.clone()
.or_else(|| get_rustdoc(&input.attrs).ok().flatten())
.map(|s| quote! { Some(#s) })
.unwrap_or_else(|| quote! {None});
let mut registry_types = Vec::new();
let mut possible_types = Vec::new();
let mut get_introspection_typename = Vec::new();
let mut collect_all_fields = Vec::new();
for variant in s.variants.iter() {
let enum_name = &variant.ident;
let field = match &variant.fields {
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => fields.unnamed.first().unwrap(),
Fields::Unnamed(_) => {
return Err(Error::new_spanned(
variant,
"Only single value variants are supported",
))
}
Fields::Unit => {
return Err(Error::new_spanned(
variant,
"Empty variants are not supported",
))
}
Fields::Named(_) => {
return Err(Error::new_spanned(
variant,
"Variants with named fields are not supported",
))
}
};
if let Type::Path(p) = &field.ty {
// This validates that the field type wasn't already used
if !enum_items.insert(p) {
return Err(Error::new_spanned(
field,
"This type already used in another variant",
));
}
enum_names.push(enum_name);
type_into_impls.push(quote! {
#[allow(clippy::all, clippy::pedantic)]
impl #generics ::std::convert::From<#p> for #ident #generics {
fn from(obj: #p) -> Self {
#ident::#enum_name(obj)
}
}
});
registry_types.push(quote! {
<#p as #crate_name::Type>::create_type_info(registry);
});
possible_types.push(quote! {
possible_types.insert(<#p as #crate_name::Type>::type_name().to_string());
});
get_introspection_typename.push(quote! {
#ident::#enum_name(obj) => <#p as #crate_name::Type>::type_name()
});
collect_all_fields.push(quote! {
#ident::#enum_name(obj) => obj.collect_all_fields(ctx, fields)
});
} else {
return Err(Error::new_spanned(field, "Invalid type"));
}
}
let expanded = quote! {
#(#type_into_impls)*
#[allow(clippy::all, clippy::pedantic)]
impl #generics #crate_name::Type for #ident #generics {
fn type_name() -> ::std::borrow::Cow<'static, str> {
::std::borrow::Cow::Borrowed(#gql_typename)
}
fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, str> {
match self {
#(#get_introspection_typename),*
}
}
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> String {
registry.create_type::<Self, _>(|registry| {
#(#registry_types)*
#crate_name::registry::MetaType::Union {
name: #gql_typename.to_string(),
description: #desc,
possible_types: {
let mut possible_types = #crate_name::indexmap::IndexSet::new();
#(#possible_types)*
possible_types
}
}
})
}
}
#[allow(clippy::all, clippy::pedantic)]
#[#crate_name::async_trait::async_trait]
impl #generics #crate_name::resolver_utils::ObjectType for #ident #generics {
async fn resolve_field(&self, ctx: &#crate_name::Context<'_>) -> #crate_name::ServerResult<::std::option::Option<#crate_name::serde_json::Value>> {
Ok(None)
}
fn collect_all_fields<'a>(&'a self, ctx: &#crate_name::ContextSelectionSet<'a>, fields: &mut #crate_name::resolver_utils::Fields<'a>) -> #crate_name::ServerResult<()> {
match self {
#(#collect_all_fields),*
}
}
}
#[allow(clippy::all, clippy::pedantic)]
#[#crate_name::async_trait::async_trait]
impl #generics #crate_name::OutputValueType for #ident #generics {
async fn resolve(&self, ctx: &#crate_name::ContextSelectionSet<'_>, _field: &#crate_name::Positioned<#crate_name::parser::types::Field>) -> #crate_name::ServerResult<#crate_name::serde_json::Value> {
#crate_name::resolver_utils::resolve_object(ctx, self).await
}
}
};
Ok(expanded.into())
}