async-graphql/derive/src/object.rs

531 lines
24 KiB
Rust
Raw Normal View History

2020-10-16 02:45:27 +00:00
use proc_macro::TokenStream;
2021-01-10 03:21:47 +00:00
use proc_macro2::Span;
2020-10-16 02:45:27 +00:00
use quote::quote;
use syn::ext::IdentExt;
use syn::{Block, Error, Ident, ImplItem, ItemImpl, ReturnType};
2020-10-16 02:45:27 +00:00
2020-12-18 06:59:37 +00:00
use crate::args::{self, ComplexityType, RenameRuleExt, RenameTarget};
2020-03-06 15:58:43 +00:00
use crate::output_type::OutputType;
2020-09-28 09:44:00 +00:00
use crate::utils::{
extract_input_args, gen_deprecation, generate_default, generate_guards, generate_validator,
get_cfg_attrs, get_crate_name, get_param_getter_ident, get_rustdoc, get_type_path_and_name,
parse_complexity_expr, parse_graphql_attrs, remove_graphql_attrs, visible_fn, GeneratorResult,
2020-09-28 09:44:00 +00:00
};
2020-03-05 06:23:55 +00:00
2020-09-28 09:44:00 +00:00
pub fn generate(
object_args: &args::Object,
item_impl: &mut ItemImpl,
) -> GeneratorResult<TokenStream> {
2020-03-02 00:24:49 +00:00
let crate_name = get_crate_name(object_args.internal);
let (self_ty, self_name) = get_type_path_and_name(item_impl.self_ty.as_ref())?;
2020-03-05 06:23:55 +00:00
let generics = &item_impl.generics;
2021-01-10 03:21:47 +00:00
let generics_params = &generics.params;
let where_clause = &item_impl.generics.where_clause;
2020-04-09 14:03:09 +00:00
let extends = object_args.extends;
2020-03-01 10:54:34 +00:00
let gql_typename = object_args
.name
.clone()
2020-10-14 09:08:57 +00:00
.unwrap_or_else(|| RenameTarget::Type.rename(self_name.clone()));
2021-01-10 03:21:47 +00:00
let shadow_type = Ident::new(&format!("__Shadow{}", gql_typename), Span::call_site());
2020-03-19 09:20:12 +00:00
let desc = if object_args.use_type_description {
quote! { ::std::option::Option::Some(<Self as #crate_name::Description>::description()) }
} else {
get_rustdoc(&item_impl.attrs)?
.map(|s| quote!(::std::option::Option::Some(#s)))
.unwrap_or_else(|| quote!(::std::option::Option::None))
};
2020-03-05 06:23:55 +00:00
2020-03-01 10:54:34 +00:00
let mut resolvers = Vec::new();
2020-03-03 03:48:00 +00:00
let mut schema_fields = Vec::new();
2020-04-09 14:03:09 +00:00
let mut find_entities = Vec::new();
let mut add_keys = Vec::new();
let mut create_entity_types = Vec::new();
2020-03-01 10:54:34 +00:00
2020-03-05 06:23:55 +00:00
for item in &mut item_impl.items {
if let ImplItem::Method(method) = item {
2020-09-28 09:44:00 +00:00
let method_args: args::ObjectField =
parse_graphql_attrs(&method.attrs)?.unwrap_or_default();
if method_args.entity {
let cfg_attrs = get_cfg_attrs(&method.attrs);
2020-06-02 04:02:14 +00:00
if method.sig.asyncness.is_none() {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(&method, "Must be asynchronous").into());
2020-06-02 04:02:14 +00:00
}
let args = extract_input_args(&crate_name, method)?;
2020-04-27 04:57:52 +00:00
let ty = match &method.sig.output {
ReturnType::Type(_, ty) => OutputType::parse(ty)?,
ReturnType::Default => {
return Err(Error::new_spanned(
&method.sig.output,
"Resolver must have a return type",
)
.into())
2020-04-27 04:57:52 +00:00
}
};
2020-05-01 23:57:34 +00:00
2020-04-27 04:57:52 +00:00
let entity_type = ty.value_type();
let mut key_pat = Vec::new();
let mut key_getter = Vec::new();
let mut use_keys = Vec::new();
let mut get_federation_key = Vec::new();
let mut requires_getter = Vec::new();
2020-06-19 04:49:45 +00:00
let all_key = args.iter().all(|(_, _, arg)| !arg.key);
2020-04-27 04:57:52 +00:00
if args.is_empty() {
return Err(Error::new_spanned(
method,
"Entity need to have at least one key.",
2020-09-28 09:44:00 +00:00
)
.into());
}
for (ident, ty, args::Argument { name, key, .. }) in &args {
2020-06-19 04:49:45 +00:00
let is_key = all_key || *key;
2020-10-14 09:08:57 +00:00
let name = name.clone().unwrap_or_else(|| {
object_args
.rename_args
.rename(ident.ident.unraw().to_string(), RenameTarget::Argument)
});
2020-04-27 04:57:52 +00:00
if is_key {
get_federation_key.push(quote! {
if let Some(fields) = <#ty as #crate_name::InputType>::federation_fields() {
key_str.push(format!("{} {}", #name, fields));
} else {
key_str.push(#name.to_string());
}
});
2020-04-27 04:57:52 +00:00
key_pat.push(quote! {
2020-10-16 10:37:59 +00:00
::std::option::Option::Some(#ident)
});
key_getter.push(quote! {
params.get(#name).and_then(|value| {
let value: ::std::option::Option<#ty> = #crate_name::InputType::parse(::std::option::Option::Some(::std::clone::Clone::clone(&value))).ok();
value
})
});
use_keys.push(ident);
} else {
// requires
requires_getter.push(quote! {
let #ident: #ty = #crate_name::InputType::parse(params.get(#name).cloned()).
map_err(|err| err.into_server_error(ctx.item.pos))?;
});
use_keys.push(ident);
}
2020-04-27 04:57:52 +00:00
}
add_keys.push(quote! {
{
let mut key_str = Vec::new();
#(#get_federation_key)*
registry.add_keys(&<#entity_type as #crate_name::Type>::type_name(), &key_str.join(" "));
}
});
2020-04-27 04:57:52 +00:00
create_entity_types.push(
quote! { <#entity_type as #crate_name::Type>::create_type_info(registry); },
);
let field_ident = &method.sig.ident;
2020-05-01 23:57:34 +00:00
if let OutputType::Value(inner_ty) = &ty {
let block = &method.block;
2020-05-03 23:59:30 +00:00
let new_block = quote!({
{
let value:#inner_ty = async move #block.await;
2020-10-16 10:37:59 +00:00
::std::result::Result::Ok(value)
2020-05-03 23:59:30 +00:00
}
});
method.block = syn::parse2::<Block>(new_block).expect("invalid block");
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
method.sig.output =
syn::parse2::<ReturnType>(quote! { -> #crate_name::Result<#inner_ty> })
.expect("invalid result type");
2020-05-01 23:57:34 +00:00
}
let do_find = quote! {
self.#field_ident(ctx, #(#use_keys),*)
.await.map_err(|err| ::std::convert::Into::<#crate_name::Error>::into(err)
2021-06-07 12:51:20 +00:00
.into_server_error(ctx.item.pos))
};
2020-05-01 23:57:34 +00:00
2020-04-27 04:57:52 +00:00
find_entities.push((
args.len(),
quote! {
#(#cfg_attrs)*
2020-04-27 04:57:52 +00:00
if typename == &<#entity_type as #crate_name::Type>::type_name() {
if let (#(#key_pat),*) = (#(#key_getter),*) {
2021-06-07 12:51:20 +00:00
let f = async move {
#(#requires_getter)*
#do_find
};
let obj = f.await.map_err(|err| ctx.set_error_path(err))?;
2020-09-12 16:42:15 +00:00
let ctx_obj = ctx.with_selection_set(&ctx.item.node.selection_set);
2021-06-07 12:51:20 +00:00
return #crate_name::OutputType::resolve(&obj, &ctx_obj, ctx.item).await.map(::std::option::Option::Some);
2020-04-27 04:57:52 +00:00
}
}
},
));
2020-09-28 09:44:00 +00:00
} else if !method_args.skip {
if method.sig.asyncness.is_none() {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(&method, "Must be asynchronous").into());
}
2020-10-14 09:08:57 +00:00
let field_name = method_args.name.clone().unwrap_or_else(|| {
object_args
.rename_fields
.rename(method.sig.ident.unraw().to_string(), RenameTarget::Field)
});
2020-09-28 09:44:00 +00:00
let field_desc = get_rustdoc(&method.attrs)?
2020-10-16 10:37:59 +00:00
.map(|s| quote! { ::std::option::Option::Some(#s) })
.unwrap_or_else(|| quote! {::std::option::Option::None});
let field_deprecation = gen_deprecation(&method_args.deprecation, &crate_name);
2020-09-28 09:44:00 +00:00
let external = method_args.external;
let requires = match &method_args.requires {
2020-10-16 10:37:59 +00:00
Some(requires) => quote! { ::std::option::Option::Some(#requires) },
None => quote! { ::std::option::Option::None },
2020-04-09 14:03:09 +00:00
};
2020-09-28 09:44:00 +00:00
let provides = match &method_args.provides {
2020-10-16 10:37:59 +00:00
Some(provides) => quote! { ::std::option::Option::Some(#provides) },
None => quote! { ::std::option::Option::None },
2020-04-09 14:03:09 +00:00
};
2020-03-22 08:45:59 +00:00
let cache_control = {
2020-09-28 09:44:00 +00:00
let public = method_args.cache_control.is_public();
let max_age = method_args.cache_control.max_age;
2020-03-22 08:45:59 +00:00
quote! {
#crate_name::CacheControl {
public: #public,
max_age: #max_age,
}
}
};
let cfg_attrs = get_cfg_attrs(&method.attrs);
2020-03-05 06:23:55 +00:00
let args = extract_input_args(&crate_name, method)?;
2020-03-05 06:23:55 +00:00
let mut schema_args = Vec::new();
let mut use_params = Vec::new();
let mut get_params = Vec::new();
let ty = match &method.sig.output {
ReturnType::Type(_, ty) => OutputType::parse(ty)?,
ReturnType::Default => {
return Err(Error::new_spanned(
&method.sig.output,
"Resolver must have a return type",
)
.into())
}
};
2020-03-04 02:38:07 +00:00
2020-03-05 06:23:55 +00:00
for (
ident,
ty,
args::Argument {
name,
desc,
default,
2020-09-28 09:44:00 +00:00
default_with,
2020-03-22 01:34:32 +00:00
validator,
visible,
secret,
..
2020-03-05 06:23:55 +00:00
},
2020-12-18 06:59:37 +00:00
) in &args
2020-03-05 06:23:55 +00:00
{
2020-10-14 09:08:57 +00:00
let name = name.clone().unwrap_or_else(|| {
object_args
.rename_args
.rename(ident.ident.unraw().to_string(), RenameTarget::Argument)
});
2020-03-05 06:23:55 +00:00
let desc = desc
.as_ref()
2020-10-16 10:37:59 +00:00
.map(|s| quote! {::std::option::Option::Some(#s)})
.unwrap_or_else(|| quote! {::std::option::Option::None});
2020-09-28 09:44:00 +00:00
let default = generate_default(&default, &default_with)?;
2020-03-05 06:23:55 +00:00
let schema_default = default
.as_ref()
.map(|value| {
2020-10-16 19:21:46 +00:00
quote! {
::std::option::Option::Some(::std::string::ToString::to_string(
&<#ty as #crate_name::InputType>::to_value(&#value)
2020-10-16 19:21:46 +00:00
))
}
2020-03-05 06:23:55 +00:00
})
2020-10-16 10:37:59 +00:00
.unwrap_or_else(|| quote! {::std::option::Option::None});
2020-03-05 06:23:55 +00:00
2020-09-28 09:44:00 +00:00
let validator = match &validator {
Some(meta) => {
let stream = generate_validator(&crate_name, meta)?;
2020-10-16 10:37:59 +00:00
quote!(::std::option::Option::Some(#stream))
2020-09-28 09:44:00 +00:00
}
2020-10-16 10:37:59 +00:00
None => quote!(::std::option::Option::None),
2020-09-28 09:44:00 +00:00
};
let visible = visible_fn(&visible);
2020-03-05 06:23:55 +00:00
schema_args.push(quote! {
args.insert(#name, #crate_name::registry::MetaInputValue {
2020-03-05 06:23:55 +00:00
name: #name,
description: #desc,
2020-03-19 09:20:12 +00:00
ty: <#ty as #crate_name::Type>::create_type_info(registry),
2020-03-05 06:23:55 +00:00
default_value: #schema_default,
2020-03-22 01:34:32 +00:00
validator: #validator,
visible: #visible,
is_secret: #secret,
2020-03-08 12:35:36 +00:00
});
2020-03-05 06:23:55 +00:00
});
2020-08-17 13:48:53 +00:00
let param_ident = &ident.ident;
use_params.push(quote! { #param_ident });
2020-03-05 06:23:55 +00:00
let default = match default {
2020-10-16 10:37:59 +00:00
Some(default) => {
quote! { ::std::option::Option::Some(|| -> #ty { #default }) }
}
None => quote! { ::std::option::Option::None },
2020-03-05 06:23:55 +00:00
};
// We're generating a new identifier,
// so remove the 'r#` prefix if present
let param_getter_name =
get_param_getter_ident(&ident.ident.unraw().to_string());
2020-03-05 06:23:55 +00:00
get_params.push(quote! {
2020-10-14 09:08:57 +00:00
#[allow(non_snake_case)]
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
let #param_getter_name = || -> #crate_name::ServerResult<#ty> { ctx.param_value(#name, #default) };
2020-10-14 09:08:57 +00:00
#[allow(non_snake_case)]
2020-06-03 06:50:06 +00:00
let #ident: #ty = #param_getter_name()?;
2020-03-05 06:23:55 +00:00
});
2020-03-03 03:48:00 +00:00
}
2020-03-01 10:54:34 +00:00
let schema_ty = ty.value_type();
let visible = visible_fn(&method_args.visible);
2020-03-22 08:45:59 +00:00
2020-12-18 06:59:37 +00:00
let complexity = if let Some(complexity) = &method_args.complexity {
match complexity {
ComplexityType::Const(n) => {
quote! { ::std::option::Option::Some(#crate_name::registry::ComplexityType::Const(#n)) }
}
ComplexityType::Fn(s) => {
let (variables, expr) = parse_complexity_expr(s)?;
let mut parse_args = Vec::new();
for variable in variables {
if let Some((
ident,
ty,
args::Argument {
name,
default,
default_with,
..
},
)) = args
.iter()
.find(|(pat_ident, _, _)| pat_ident.ident == variable)
{
let default = match generate_default(&default, &default_with)? {
Some(default) => {
quote! { ::std::option::Option::Some(|| -> #ty { #default }) }
}
None => quote! { ::std::option::Option::None },
};
2020-12-18 06:59:37 +00:00
let name = name.clone().unwrap_or_else(|| {
object_args.rename_args.rename(
ident.ident.unraw().to_string(),
RenameTarget::Argument,
)
});
parse_args.push(quote! {
let #ident: #ty = __ctx.param_value(__variables_definition, __field, #name, #default)?;
});
2020-12-18 06:59:37 +00:00
}
}
quote! {
Some(#crate_name::registry::ComplexityType::Fn(|__ctx, __variables_definition, __field, child_complexity| {
#(#parse_args)*
Ok(#expr)
}))
}
}
}
} else {
quote! { ::std::option::Option::None }
};
2020-03-05 06:23:55 +00:00
schema_fields.push(quote! {
#(#cfg_attrs)*
2020-10-16 19:21:46 +00:00
fields.insert(::std::borrow::ToOwned::to_owned(#field_name), #crate_name::registry::MetaField {
name: ::std::borrow::ToOwned::to_owned(#field_name),
2020-03-05 06:23:55 +00:00
description: #field_desc,
2020-03-08 12:35:36 +00:00
args: {
let mut args = #crate_name::indexmap::IndexMap::new();
2020-03-08 12:35:36 +00:00
#(#schema_args)*
args
},
2020-03-19 09:20:12 +00:00
ty: <#schema_ty as #crate_name::Type>::create_type_info(registry),
2020-03-05 06:23:55 +00:00
deprecation: #field_deprecation,
2020-03-22 08:45:59 +00:00
cache_control: #cache_control,
2020-04-09 14:03:09 +00:00
external: #external,
provides: #provides,
requires: #requires,
visible: #visible,
2020-12-18 06:59:37 +00:00
compute_complexity: #complexity,
2020-03-08 12:35:36 +00:00
});
2020-03-02 11:25:21 +00:00
});
2020-03-05 06:23:55 +00:00
let field_ident = &method.sig.ident;
2020-05-01 23:57:34 +00:00
if let OutputType::Value(inner_ty) = &ty {
let block = &method.block;
2020-05-03 23:59:30 +00:00
let new_block = quote!({
{
2021-01-10 03:21:47 +00:00
::std::result::Result::Ok(async move {
let value:#inner_ty = #block;
value
}.await)
2020-05-03 23:59:30 +00:00
}
});
method.block = syn::parse2::<Block>(new_block).expect("invalid block");
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
method.sig.output =
syn::parse2::<ReturnType>(quote! { -> #crate_name::Result<#inner_ty> })
.expect("invalid result type");
2020-05-01 23:57:34 +00:00
}
2020-05-01 23:57:34 +00:00
let resolve_obj = quote! {
{
2020-05-05 05:02:24 +00:00
let res = self.#field_ident(ctx, #(#use_params),*).await;
2021-06-07 12:51:20 +00:00
res.map_err(|err| ::std::convert::Into::<#crate_name::Error>::into(err).into_server_error(ctx.item.pos))
2020-03-05 06:23:55 +00:00
}
};
2020-09-28 09:44:00 +00:00
let guard = match &method_args.guard {
Some(meta_list) => generate_guards(&crate_name, meta_list)?,
None => None,
};
2020-09-30 17:24:24 +00:00
let guard = guard.map(|guard| {
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
quote! {
#guard.check(ctx).await.map_err(|err| err.into_server_error(ctx.item.pos))?;
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
}
});
2020-09-28 09:44:00 +00:00
2020-03-05 06:23:55 +00:00
resolvers.push(quote! {
#(#cfg_attrs)*
2020-09-12 16:42:15 +00:00
if ctx.item.node.name.node == #field_name {
2021-06-07 12:51:20 +00:00
let f = async move {
#(#get_params)*
#guard
#resolve_obj
};
let obj = f.await.map_err(|err| ctx.set_error_path(err))?;
2020-09-12 16:42:15 +00:00
let ctx_obj = ctx.with_selection_set(&ctx.item.node.selection_set);
2021-06-07 12:51:20 +00:00
return #crate_name::OutputType::resolve(&obj, &ctx_obj, ctx.item).await.map(::std::option::Option::Some);
2020-03-05 06:23:55 +00:00
}
2020-03-02 11:25:21 +00:00
});
2020-03-03 03:48:00 +00:00
}
2020-09-28 09:44:00 +00:00
remove_graphql_attrs(&mut method.attrs);
2020-03-05 06:23:55 +00:00
}
2020-03-02 00:24:49 +00:00
}
2020-03-22 08:45:59 +00:00
let cache_control = {
2020-09-28 09:44:00 +00:00
let public = object_args.cache_control.is_public();
2020-03-22 08:45:59 +00:00
let max_age = object_args.cache_control.max_age;
quote! {
#crate_name::CacheControl {
public: #public,
max_age: #max_age,
}
}
};
2020-04-09 14:03:09 +00:00
find_entities.sort_by(|(a, _), (b, _)| b.cmp(a));
let find_entities_iter = find_entities.iter().map(|(_, code)| code);
if resolvers.is_empty() && create_entity_types.is_empty() {
return Err(Error::new_spanned(
&self_ty,
2020-10-22 02:11:47 +00:00
"A GraphQL Object type must define one or more fields.",
)
.into());
}
let visible = visible_fn(&object_args.visible);
let resolve_container = if object_args.serial {
quote! { #crate_name::resolver_utils::resolve_container_serial(ctx, self).await }
} else {
quote! { #crate_name::resolver_utils::resolve_container(ctx, self).await }
};
2021-01-10 03:21:47 +00:00
2020-03-01 10:54:34 +00:00
let expanded = quote! {
2020-03-05 06:23:55 +00:00
#item_impl
2020-03-01 10:54:34 +00:00
2021-01-10 03:21:47 +00:00
#[allow(non_snake_case)]
type #shadow_type<#generics_params> = #self_ty;
#[allow(clippy::all, clippy::pedantic)]
2021-01-10 03:21:47 +00:00
impl #generics #crate_name::Type for #shadow_type<#generics_params> #where_clause {
2020-10-16 10:37:59 +00:00
fn type_name() -> ::std::borrow::Cow<'static, ::std::primitive::str> {
::std::borrow::Cow::Borrowed(#gql_typename)
2020-03-01 10:54:34 +00:00
}
2020-03-03 03:48:00 +00:00
2020-10-16 10:37:59 +00:00
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> ::std::string::String {
let ty = registry.create_type::<Self, _>(|registry| #crate_name::registry::MetaType::Object {
2020-10-16 19:21:46 +00:00
name: ::std::borrow::ToOwned::to_owned(#gql_typename),
2020-03-03 11:15:18 +00:00
description: #desc,
2020-03-08 12:35:36 +00:00
fields: {
let mut fields = #crate_name::indexmap::IndexMap::new();
2020-03-08 12:35:36 +00:00
#(#schema_fields)*
fields
},
2020-03-22 08:45:59 +00:00
cache_control: #cache_control,
2020-04-09 14:03:09 +00:00
extends: #extends,
2020-10-16 10:37:59 +00:00
keys: ::std::option::Option::None,
visible: #visible,
2020-04-09 14:03:09 +00:00
});
#(#create_entity_types)*
#(#add_keys)*
ty
2020-03-03 03:48:00 +00:00
}
2020-03-01 10:54:34 +00:00
}
#[allow(clippy::all, clippy::pedantic, clippy::suspicious_else_formatting)]
2020-08-17 13:48:53 +00:00
#[allow(unused_braces, unused_variables, unused_parens, unused_mut)]
2020-03-02 00:24:49 +00:00
#[#crate_name::async_trait::async_trait]
2021-01-10 03:21:47 +00:00
impl#generics #crate_name::resolver_utils::ContainerType for #shadow_type<#generics_params> #where_clause {
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>> {
2020-03-06 15:58:43 +00:00
#(#resolvers)*
2020-10-16 10:37:59 +00:00
::std::result::Result::Ok(::std::option::Option::None)
2020-03-01 10:54:34 +00:00
}
2020-04-09 14:03:09 +00:00
2020-10-10 02:32:43 +00:00
async fn find_entity(&self, ctx: &#crate_name::Context<'_>, params: &#crate_name::Value) -> #crate_name::ServerResult<::std::option::Option<#crate_name::Value>> {
2020-04-09 14:03:09 +00:00
let params = match params {
#crate_name::Value::Object(params) => params,
2020-10-16 10:37:59 +00:00
_ => return ::std::result::Result::Ok(::std::option::Option::None),
2020-04-09 14:03:09 +00:00
};
2020-10-16 10:37:59 +00:00
let typename = if let ::std::option::Option::Some(#crate_name::Value::String(typename)) = params.get("__typename") {
2020-04-09 14:03:09 +00:00
typename
} else {
2020-10-16 10:37:59 +00:00
return ::std::result::Result::Err(
#crate_name::ServerError::new(r#""__typename" must be an existing string."#, ::std::option::Option::Some(ctx.item.pos))
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
);
2020-04-09 14:03:09 +00:00
};
#(#find_entities_iter)*
2020-10-16 10:37:59 +00:00
::std::result::Result::Ok(::std::option::Option::None)
2020-04-09 14:03:09 +00:00
}
2020-03-01 10:54:34 +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]
2021-01-10 03:21:47 +00:00
impl #generics #crate_name::OutputType for #shadow_type<#generics_params> #where_clause {
2021-06-07 12:51:20 +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> {
#resolve_container
2020-03-19 09:20:12 +00:00
}
}
2021-01-10 03:21:47 +00:00
impl #generics #crate_name::ObjectType for #shadow_type<#generics_params> #where_clause {}
2020-03-01 10:54:34 +00:00
};
Ok(expanded.into())
}