async-graphql/derive/src/union.rs

186 lines
7.0 KiB
Rust
Raw Normal View History

2020-03-08 01:21:29 +00:00
use crate::args;
2020-09-28 09:44:00 +00:00
use crate::utils::{get_crate_name, get_rustdoc, GeneratorResult};
use darling::ast::{Data, Style};
2020-03-08 01:21:29 +00:00
use proc_macro::TokenStream;
use quote::quote;
use std::collections::HashSet;
2020-09-28 09:44:00 +00:00
use syn::{Error, Type};
2020-03-08 01:21:29 +00:00
2020-09-28 09:44:00 +00:00
pub fn generate(union_args: &args::Union) -> GeneratorResult<TokenStream> {
let crate_name = get_crate_name(union_args.internal);
2020-09-28 09:44:00 +00:00
let ident = &union_args.ident;
let generics = &union_args.generics;
let s = match &union_args.data {
Data::Enum(s) => s,
_ => {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(&ident, "Union can only be applied to an enum.").into())
}
2020-03-08 01:21:29 +00:00
};
let mut enum_names = Vec::new();
let mut enum_items = HashSet::new();
2020-03-08 01:21:29 +00:00
let mut type_into_impls = Vec::new();
let gql_typename = union_args.name.clone().unwrap_or_else(|| ident.to_string());
2020-03-19 09:20:12 +00:00
2020-09-28 09:44:00 +00:00
let desc = get_rustdoc(&union_args.attrs)?
.map(|s| quote! { Some(#s) })
2020-03-08 01:21:29 +00:00
.unwrap_or_else(|| quote! {None});
2020-03-08 01:21:29 +00:00
let mut registry_types = Vec::new();
let mut possible_types = Vec::new();
let mut get_introspection_typename = Vec::new();
2020-09-12 09:29:52 +00:00
let mut collect_all_fields = Vec::new();
2020-03-08 01:21:29 +00:00
2020-09-28 09:44:00 +00:00
for variant in s {
let enum_name = &variant.ident;
2020-09-28 09:44:00 +00:00
let ty = match variant.fields.style {
Style::Tuple if variant.fields.fields.len() == 1 => &variant.fields.fields[0],
Style::Tuple => {
return Err(Error::new_spanned(
2020-09-28 09:44:00 +00:00
enum_name,
"Only single value variants are supported",
2020-09-28 09:44:00 +00:00
)
.into())
}
2020-09-28 09:44:00 +00:00
Style::Unit => {
return Err(
Error::new_spanned(enum_name, "Empty variants are not supported").into(),
)
}
2020-09-28 09:44:00 +00:00
Style::Struct => {
return Err(Error::new_spanned(
2020-09-28 09:44:00 +00:00
enum_name,
"Variants with named fields are not supported",
2020-09-28 09:44:00 +00:00
)
.into())
}
};
2020-09-28 09:44:00 +00:00
if let Type::Path(p) = &ty {
// This validates that the field type wasn't already used
if !enum_items.insert(p) {
2020-09-28 09:44:00 +00:00
return Err(
Error::new_spanned(&ty, "This type already used in another variant").into(),
);
}
2020-03-08 01:21:29 +00:00
enum_names.push(enum_name);
2020-09-28 09:44:00 +00:00
if !variant.flatten {
type_into_impls.push(quote! {
2020-09-29 23:45:48 +00:00
#crate_name::static_assertions::assert_impl_one!(#p: #crate_name::ObjectType);
#[allow(clippy::all, clippy::pedantic)]
impl #generics ::std::convert::From<#p> for #ident #generics {
fn from(obj: #p) -> Self {
#ident::#enum_name(obj)
}
2020-03-08 01:21:29 +00:00
}
});
} else {
type_into_impls.push(quote! {
2020-09-29 23:45:48 +00:00
#crate_name::static_assertions::assert_impl_one!(#p: #crate_name::UnionType);
#[allow(clippy::all, clippy::pedantic)]
impl #generics ::std::convert::From<#p> for #ident #generics {
fn from(obj: #p) -> Self {
#ident::#enum_name(obj)
}
}
});
}
2020-03-08 01:21:29 +00:00
registry_types.push(quote! {
2020-03-19 09:20:12 +00:00
<#p as #crate_name::Type>::create_type_info(registry);
2020-03-08 01:21:29 +00:00
});
2020-09-28 09:44:00 +00:00
if !variant.flatten {
possible_types.push(quote! {
possible_types.insert(<#p as #crate_name::Type>::type_name().to_string());
});
} else {
possible_types.push(quote! {
if let Some(#crate_name::registry::MetaType::Union { possible_types: possible_types2, .. }) =
registry.types.get(&*<#p as #crate_name::Type>::type_name()) {
possible_types.extend(possible_types2.clone());
}
});
}
2020-09-28 09:44:00 +00:00
if !variant.flatten {
get_introspection_typename.push(quote! {
#ident::#enum_name(obj) => <#p as #crate_name::Type>::type_name()
});
} else {
get_introspection_typename.push(quote! {
#ident::#enum_name(obj) => <#p as #crate_name::Type>::introspection_type_name(obj)
});
}
2020-09-12 09:29:52 +00:00
collect_all_fields.push(quote! {
#ident::#enum_name(obj) => obj.collect_all_fields(ctx, fields)
});
2020-03-08 01:21:29 +00:00
} else {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(ty, "Invalid type").into());
2020-03-08 01:21:29 +00:00
}
}
let expanded = quote! {
#(#type_into_impls)*
#[allow(clippy::all, clippy::pedantic)]
2020-03-19 09:20:12 +00:00
impl #generics #crate_name::Type for #ident #generics {
fn type_name() -> ::std::borrow::Cow<'static, str> {
::std::borrow::Cow::Borrowed(#gql_typename)
2020-03-08 01:21:29 +00:00
}
fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, str> {
match self {
#(#get_introspection_typename),*
}
}
2020-03-08 01:21:29 +00:00
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> String {
registry.create_type::<Self, _>(|registry| {
#(#registry_types)*
#crate_name::registry::MetaType::Union {
2020-03-19 09:33:33 +00:00
name: #gql_typename.to_string(),
2020-03-08 01:21:29 +00:00
description: #desc,
2020-03-10 10:07:47 +00:00
possible_types: {
let mut possible_types = #crate_name::indexmap::IndexSet::new();
2020-03-10 10:07:47 +00:00
#(#possible_types)*
possible_types
}
2020-03-08 01:21:29 +00:00
}
})
}
}
#[allow(clippy::all, clippy::pedantic)]
2020-03-08 01:21:29 +00:00
#[#crate_name::async_trait::async_trait]
2020-09-29 23:45:48 +00:00
impl #generics #crate_name::resolver_utils::ContainerType for #ident #generics {
2020-10-10 02:32:43 +00:00
async fn resolve_field(&self, ctx: &#crate_name::Context<'_>) -> #crate_name::ServerResult<::std::option::Option<#crate_name::Value>> {
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(None)
2020-03-08 01:21:29 +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
fn collect_all_fields<'a>(&'a self, ctx: &#crate_name::ContextSelectionSet<'a>, fields: &mut #crate_name::resolver_utils::Fields<'a>) -> #crate_name::ServerResult<()> {
2020-09-12 09:29:52 +00:00
match self {
#(#collect_all_fields),*
}
2020-03-08 01:21:29 +00:00
}
}
2020-03-19 09:20:12 +00:00
#[allow(clippy::all, clippy::pedantic)]
2020-03-19 09:20:12 +00:00
#[#crate_name::async_trait::async_trait]
impl #generics #crate_name::OutputValueType for #ident #generics {
2020-10-10 02:32:43 +00:00
async fn resolve(&self, ctx: &#crate_name::ContextSelectionSet<'_>, _field: &#crate_name::Positioned<#crate_name::parser::types::Field>) -> #crate_name::ServerResult<#crate_name::Value> {
2020-09-29 23:45:48 +00:00
#crate_name::resolver_utils::resolve_container(ctx, self).await
2020-03-19 09:20:12 +00:00
}
}
2020-09-29 23:45:48 +00:00
impl #generics #crate_name::UnionType for #ident #generics {}
2020-03-08 01:21:29 +00:00
};
Ok(expanded.into())
}