Add SimpleObject macro

This commit is contained in:
sunli 2020-03-27 10:20:20 +08:00
parent dd6af84902
commit 15fbe9502a
4 changed files with 225 additions and 10 deletions

View File

@ -8,6 +8,7 @@ mod input_object;
mod interface;
mod object;
mod output_type;
mod simple_object;
mod subscription;
mod union;
mod utils;
@ -30,6 +31,20 @@ pub fn Object(args: TokenStream, input: TokenStream) -> TokenStream {
}
}
#[proc_macro_attribute]
#[allow(non_snake_case)]
pub fn SimpleObject(args: TokenStream, input: TokenStream) -> TokenStream {
let object_args = match args::Object::parse(parse_macro_input!(args as AttributeArgs)) {
Ok(object_args) => object_args,
Err(err) => return err.to_compile_error().into(),
};
let mut derive_input = parse_macro_input!(input as DeriveInput);
match simple_object::generate(&object_args, &mut derive_input) {
Ok(expanded) => expanded,
Err(err) => err.to_compile_error().into(),
}
}
#[proc_macro_attribute]
#[allow(non_snake_case)]
pub fn Enum(args: TokenStream, input: TokenStream) -> TokenStream {

View File

@ -0,0 +1,151 @@
use crate::args;
use crate::utils::{check_reserved_name, get_crate_name};
use inflector::Inflector;
use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Error, Fields, Result};
pub fn generate(object_args: &args::Object, input: &mut DeriveInput) -> Result<TokenStream> {
let crate_name = get_crate_name(object_args.internal);
let ident = &input.ident;
let generics = &input.generics;
let s = match &mut input.data {
Data::Struct(e) => e,
_ => return Err(Error::new_spanned(input, "It should be a struct")),
};
let gql_typename = object_args
.name
.clone()
.unwrap_or_else(|| ident.to_string());
check_reserved_name(&gql_typename, object_args.internal)?;
let desc = object_args
.desc
.as_ref()
.map(|s| quote! { Some(#s) })
.unwrap_or_else(|| quote! {None});
let mut resolvers = Vec::new();
let mut schema_fields = Vec::new();
let fields = match &mut s.fields {
Fields::Named(fields) => fields,
_ => return Err(Error::new_spanned(input, "All fields must be named.")),
};
for item in &mut fields.named {
if let Some(field) = args::Field::parse(&item.attrs)? {
let field_name = field
.name
.clone()
.unwrap_or_else(|| item.ident.as_ref().unwrap().to_string().to_camel_case());
let field_desc = field
.desc
.as_ref()
.map(|s| quote! {Some(#s)})
.unwrap_or_else(|| quote! {None});
let field_deprecation = field
.deprecation
.as_ref()
.map(|s| quote! {Some(#s)})
.unwrap_or_else(|| quote! {None});
let ty = &item.ty;
let cache_control = {
let public = field.cache_control.public;
let max_age = field.cache_control.max_age;
quote! {
#crate_name::CacheControl {
public: #public,
max_age: #max_age,
}
}
};
schema_fields.push(quote! {
fields.insert(#field_name.to_string(), #crate_name::registry::Field {
name: #field_name.to_string(),
description: #field_desc,
args: Default::default(),
ty: <#ty as #crate_name::Type>::create_type_info(registry),
deprecation: #field_deprecation,
cache_control: #cache_control,
});
});
let ident = &item.ident;
resolvers.push(quote! {
if field.name.as_str() == #field_name {
let ctx_obj = ctx.with_selection_set(&field.selection_set);
return #crate_name::OutputValueType::resolve(&self.#ident, &ctx_obj).await.
map_err(|err| err.with_position(field.position).into());
}
});
item.attrs.remove(
item.attrs
.iter()
.enumerate()
.find(|(_, a)| a.path.is_ident("field"))
.map(|(idx, _)| idx)
.unwrap(),
);
}
}
let cache_control = {
let public = object_args.cache_control.public;
let max_age = object_args.cache_control.max_age;
quote! {
#crate_name::CacheControl {
public: #public,
max_age: #max_age,
}
}
};
let expanded = quote! {
#input
impl #generics #crate_name::Type for #ident {
fn type_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(#gql_typename)
}
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> String {
registry.create_type::<Self, _>(|registry| #crate_name::registry::Type::Object {
name: #gql_typename.to_string(),
description: #desc,
fields: {
let mut fields = std::collections::HashMap::new();
#(#schema_fields)*
fields
},
cache_control: #cache_control,
})
}
}
#[#crate_name::async_trait::async_trait]
impl #generics #crate_name::ObjectType for #ident #generics {
async fn resolve_field(&self, ctx: &#crate_name::Context<'_>, field: &#crate_name::graphql_parser::query::Field) -> #crate_name::Result<#crate_name::serde_json::Value> {
use #crate_name::ErrorWithPosition;
#(#resolvers)*
#crate_name::anyhow::bail!(#crate_name::QueryError::FieldNotFound {
field_name: field.name.clone(),
object: #gql_typename.to_string(),
}
.with_position(field.position));
}
}
#[#crate_name::async_trait::async_trait]
impl #generics #crate_name::OutputValueType for #ident #generics {
async fn resolve(value: &Self, ctx: &#crate_name::ContextSelectionSet<'_>) -> #crate_name::Result<#crate_name::serde_json::Value> {
#crate_name::do_resolve(ctx, value).await
}
}
};
Ok(expanded.into())
}

View File

@ -171,3 +171,9 @@ impl QueryRoot {
field(name = "appears_in", type = "&'ctx [Episode]", context)
)]
pub struct Character(Human, Droid);
#[async_graphql::SimpleObject]
struct QueryRoot1 {
#[field]
value: i32,
}

View File

@ -178,7 +178,7 @@ pub use types::{EnumItem, EnumType};
///
/// ```ignore
/// #[Object]
/// impl MyObject {
/// impl QueryRoot {
/// async fn value(&self, ctx: &Context<'_>) -> { ... }
/// }
/// ```
@ -188,12 +188,12 @@ pub use types::{EnumItem, EnumType};
/// ```rust
/// use async_graphql::*;
///
/// struct MyObject {
/// struct QueryRoot {
/// value: i32,
/// }
///
/// #[Object]
/// impl MyObject {
/// impl QueryRoot {
/// #[field(desc = "value")]
/// async fn value(&self) -> i32 {
/// self.value
@ -217,7 +217,7 @@ pub use types::{EnumItem, EnumType};
///
/// #[async_std::main]
/// async fn main() {
/// let schema = Schema::new(MyObject{ value: 10 }, EmptyMutation, EmptySubscription);
/// let schema = Schema::new(QueryRoot{ value: 10 }, EmptyMutation, EmptySubscription);
/// let res = schema.query(r#"{
/// value
/// valueRef
@ -236,6 +236,49 @@ pub use types::{EnumItem, EnumType};
/// ```
pub use async_graphql_derive::Object;
/// Define a GraphQL object
///
/// Similar to `Object`, but defined on a structure that automatically generates getters for all fields.
///
/// # Macro parameters
///
/// | Attribute | description | Type | Optional |
/// |---------------|---------------------------|----------|----------|
/// | name | Object name | string | Y |
/// | desc | Object description | string | Y |
/// | cache_control | Object cache control | [`CacheControl`](struct.CacheControl.html) | Y |
///
/// # Field parameters
///
/// | Attribute | description | Type | Optional |
/// |---------------|---------------------------|----------|----------|
/// | name | Field name | string | Y |
/// | desc | Field description | string | Y |
/// | deprecation | Field deprecation reason | string | Y |
/// | cache_control | Field cache control | [`CacheControl`](struct.CacheControl.html) | Y |
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// #[SimpleObject]
/// struct QueryRoot {
/// #[field]
/// value: i32,
/// }
///
/// #[async_std::main]
/// async fn main() {
/// let schema = Schema::new(QueryRoot{ value: 10 }, EmptyMutation, EmptySubscription);
/// let res = schema.query("{ value }").execute().await.unwrap().data;
/// assert_eq!(res, serde_json::json!({
/// "value": 10,
/// }));
/// }
/// ```
pub use async_graphql_derive::SimpleObject;
/// Define a GraphQL enum
///
/// # Macro parameters
@ -264,13 +307,13 @@ pub use async_graphql_derive::Object;
/// #[item(name = "b")] B,
/// }
///
/// struct MyObject {
/// struct QueryRoot {
/// value1: MyEnum,
/// value2: MyEnum,
/// }
///
/// #[Object]
/// impl MyObject {
/// impl QueryRoot {
/// #[field(desc = "value")]
/// async fn value1(&self) -> MyEnum {
/// self.value1
@ -284,7 +327,7 @@ pub use async_graphql_derive::Object;
///
/// #[async_std::main]
/// async fn main() {
/// let schema = Schema::new(MyObject{ value1: MyEnum::A, value2: MyEnum::B }, EmptyMutation, EmptySubscription);
/// let schema = Schema::new(QueryRoot{ value1: MyEnum::A, value2: MyEnum::B }, EmptyMutation, EmptySubscription);
/// let res = schema.query("{ value1 value2 }").execute().await.unwrap().data;
/// assert_eq!(res, serde_json::json!({ "value1": "A", "value2": "b" }));
/// }
@ -321,10 +364,10 @@ pub use async_graphql_derive::Enum;
/// b: i32,
/// }
///
/// struct MyObject;
/// struct QueryRoot;
///
/// #[Object]
/// impl MyObject {
/// impl QueryRoot {
/// #[field(desc = "value")]
/// async fn value(&self, input: MyInputObject) -> i32 {
/// input.a * input.b
@ -333,7 +376,7 @@ pub use async_graphql_derive::Enum;
///
/// #[async_std::main]
/// async fn main() {
/// let schema = Schema::new(MyObject, EmptyMutation, EmptySubscription);
/// let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);
/// let res = schema.query(r#"
/// {
/// value1: value(input:{a:9, b:3})