async-graphql/derive/src/object.rs

543 lines
24 KiB
Rust
Raw Normal View History

2020-10-16 02:45:27 +00:00
use proc_macro::TokenStream;
use quote::quote;
use syn::ext::IdentExt;
use syn::{Block, Error, FnArg, ImplItem, ItemImpl, Pat, ReturnType, Type, TypeReference};
2020-10-14 09:08:57 +00:00
use crate::args::{self, 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::{
2020-10-06 09:16:51 +00:00
generate_default, generate_guards, generate_validator, get_cfg_attrs, get_crate_name,
get_param_getter_ident, get_rustdoc, get_type_path_and_name, parse_graphql_attrs,
remove_graphql_attrs, 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;
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()));
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
}
2020-04-27 04:57:52 +00:00
let ty = match &method.sig.output {
ReturnType::Type(_, ty) => OutputType::parse(ty)?,
ReturnType::Default => {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(&method.sig.output, "Missing type").into())
2020-04-27 04:57:52 +00:00
}
};
2020-05-01 23:57:34 +00:00
let mut create_ctx = true;
2020-04-27 04:57:52 +00:00
let mut args = Vec::new();
for (idx, arg) in method.sig.inputs.iter_mut().enumerate() {
if let FnArg::Receiver(receiver) = arg {
if idx != 0 {
return Err(Error::new_spanned(
receiver,
"The self receiver must be the first parameter.",
2020-09-28 09:44:00 +00:00
)
.into());
2020-04-27 04:57:52 +00:00
}
} else if let FnArg::Typed(pat) = arg {
if idx == 0 {
return Err(Error::new_spanned(
pat,
"The self receiver must be the first parameter.",
2020-09-28 09:44:00 +00:00
)
.into());
2020-04-27 04:57:52 +00:00
}
match (&*pat.pat, &*pat.ty) {
(Pat::Ident(arg_ident), Type::Path(arg_ty)) => {
args.push((
2020-05-01 23:57:34 +00:00
arg_ident.clone(),
arg_ty.clone(),
2020-09-28 09:44:00 +00:00
parse_graphql_attrs::<args::Argument>(&pat.attrs)?
.unwrap_or_default(),
2020-04-27 04:57:52 +00:00
));
remove_graphql_attrs(&mut pat.attrs);
2020-04-27 04:57:52 +00:00
}
2020-05-01 23:57:34 +00:00
(arg, Type::Reference(TypeReference { elem, .. })) => {
2020-04-27 04:57:52 +00:00
if let Type::Path(path) = elem.as_ref() {
if idx != 1
|| path.path.segments.last().unwrap().ident != "Context"
{
return Err(Error::new_spanned(
arg,
"Only types that implement `InputType` can be used as input arguments.",
2020-09-28 09:44:00 +00:00
)
.into());
2020-05-01 23:57:34 +00:00
} else {
create_ctx = false;
2020-04-27 04:57:52 +00:00
}
}
}
2020-09-28 09:44:00 +00:00
_ => {
return Err(Error::new_spanned(arg, "Invalid argument type.").into())
}
2020-04-27 04:57:52 +00:00
}
}
}
2020-05-01 23:57:34 +00:00
if create_ctx {
2020-05-05 05:02:24 +00:00
let arg =
syn::parse2::<FnArg>(quote! { _: &#crate_name::Context<'_> }).unwrap();
2020-05-01 23:57:34 +00:00
method.sig.inputs.insert(1, arg);
}
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 keys = Vec::new();
let mut keys_str = String::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 {
if !keys_str.is_empty() {
keys_str.push(' ');
}
keys_str.push_str(&name);
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
})
});
keys.push(name);
use_keys.push(ident);
} else {
// requires
requires_getter.push(quote! {
let #ident: #ty = #crate_name::InputType::parse(params.get(#name).cloned()).
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
map_err(|err| err.into_server_error().at(ctx.item.pos))?;
});
use_keys.push(ident);
}
2020-04-27 04:57:52 +00:00
}
2020-04-27 04:57:52 +00:00
add_keys.push(quote! { registry.add_keys(&<#entity_type as #crate_name::Type>::type_name(), #keys_str); });
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
}
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 do_find = quote! { self.#field_ident(ctx, #(#use_keys),*).await.map_err(|err| err.into_server_error().at(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),*) {
#(#requires_getter)*
2020-09-12 16:42:15 +00:00
let ctx_obj = ctx.with_selection_set(&ctx.item.node.selection_set);
return #crate_name::OutputType::resolve(&#do_find, &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});
2020-09-28 09:44:00 +00:00
let field_deprecation = method_args
2020-03-05 06:23:55 +00:00
.deprecation
.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 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-05 06:23:55 +00:00
let ty = match &method.sig.output {
2020-03-06 15:58:43 +00:00
ReturnType::Type(_, ty) => OutputType::parse(ty)?,
2020-03-05 06:23:55 +00:00
ReturnType::Default => {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(&method.sig.output, "Missing type").into())
2020-03-05 06:23:55 +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
2020-05-01 23:57:34 +00:00
let mut create_ctx = true;
2020-03-05 06:23:55 +00:00
let mut args = Vec::new();
2020-03-02 11:25:21 +00:00
2020-03-05 06:23:55 +00:00
for (idx, arg) in method.sig.inputs.iter_mut().enumerate() {
if let FnArg::Receiver(receiver) = arg {
if idx != 0 {
return Err(Error::new_spanned(
receiver,
"The self receiver must be the first parameter.",
2020-09-28 09:44:00 +00:00
)
.into());
2020-03-05 06:23:55 +00:00
}
} else if let FnArg::Typed(pat) = arg {
if idx == 0 {
return Err(Error::new_spanned(
pat,
"The self receiver must be the first parameter.",
2020-09-28 09:44:00 +00:00
)
.into());
2020-03-05 06:23:55 +00:00
}
2020-03-04 02:38:07 +00:00
2020-03-05 06:23:55 +00:00
match (&*pat.pat, &*pat.ty) {
(Pat::Ident(arg_ident), Type::Path(arg_ty)) => {
2020-03-21 07:07:11 +00:00
args.push((
2020-05-01 23:57:34 +00:00
arg_ident.clone(),
arg_ty.clone(),
2020-09-28 09:44:00 +00:00
parse_graphql_attrs::<args::Argument>(&pat.attrs)?
.unwrap_or_default(),
2020-03-21 07:07:11 +00:00
));
remove_graphql_attrs(&mut pat.attrs);
2020-03-05 06:23:55 +00:00
}
2020-05-01 23:57:34 +00:00
(arg, Type::Reference(TypeReference { elem, .. })) => {
2020-03-05 06:23:55 +00:00
if let Type::Path(path) = elem.as_ref() {
if idx != 1
2020-03-21 01:32:13 +00:00
|| path.path.segments.last().unwrap().ident != "Context"
2020-03-05 06:23:55 +00:00
{
return Err(Error::new_spanned(
arg,
"Only types that implement `InputType` can be used as input arguments.",
2020-09-28 09:44:00 +00:00
)
.into());
2020-03-05 06:23:55 +00:00
}
2020-05-01 23:57:34 +00:00
create_ctx = false;
2020-03-05 06:23:55 +00:00
}
}
2020-09-28 09:44:00 +00:00
_ => {
return Err(Error::new_spanned(arg, "Invalid argument type.").into())
}
2020-03-05 06:23:55 +00:00
}
}
2020-03-04 02:38:07 +00:00
}
2020-05-01 23:57:34 +00:00
if create_ctx {
2020-05-05 05:02:24 +00:00
let arg =
syn::parse2::<FnArg>(quote! { _: &#crate_name::Context<'_> }).unwrap();
2020-05-01 23:57:34 +00:00
method.sig.inputs.insert(1, arg);
}
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();
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,
..
2020-03-05 06:23:55 +00:00
},
) in args
{
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
};
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,
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
};
2020-06-03 06:50:06 +00:00
let param_getter_name = get_param_getter_ident(&ident.ident.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();
2020-03-22 08:45:59 +00:00
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,
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!({
{
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
}
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;
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
res.map_err(|err| err.into_server_error().at(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! {
2020-05-05 05:02:24 +00:00
#guard.check(ctx).await
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
.map_err(|err| err.into_server_error().at(ctx.item.pos))?;
}
});
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 {
2020-03-05 06:23:55 +00:00
#(#get_params)*
#guard
2020-09-12 16:42:15 +00:00
let ctx_obj = ctx.with_selection_set(&ctx.item.node.selection_set);
2020-06-03 06:50:06 +00:00
let res = #resolve_obj;
return #crate_name::OutputType::resolve(&res, &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());
}
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
#[allow(clippy::all, clippy::pedantic)]
impl #generics #crate_name::Type for #self_ty #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,
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]
2020-09-29 23:45:48 +00:00
impl#generics #crate_name::resolver_utils::ContainerType for #self_ty #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(
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
#crate_name::ServerError::new(r#""__typename" must be an existing string."#)
.at(ctx.item.pos)
);
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]
impl #generics #crate_name::OutputType for #self_ty #where_clause {
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::ObjectType for #self_ty #where_clause {}
2020-03-01 10:54:34 +00:00
};
Ok(expanded.into())
}