implemented union type
This commit is contained in:
parent
0aaaec8508
commit
ce9ca29c3d
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "async-graphql"
|
||||
version = "0.9.4"
|
||||
version = "0.10.0"
|
||||
authors = ["sunli <scott_s829@163.com>"]
|
||||
edition = "2018"
|
||||
description = "The GraphQL server library implemented by rust"
|
||||
|
@ -17,7 +17,7 @@ readme = "README.md"
|
|||
default = ["chrono", "uuid"]
|
||||
|
||||
[dependencies]
|
||||
async-graphql-derive = { path = "async-graphql-derive", version = "0.9.4" }
|
||||
async-graphql-derive = { path = "async-graphql-derive", version = "0.10.0" }
|
||||
graphql-parser = "0.2.3"
|
||||
anyhow = "1.0.26"
|
||||
thiserror = "1.0.11"
|
||||
|
|
|
@ -59,7 +59,7 @@
|
|||
- [X] Field default value
|
||||
- [X] Deprecated flag
|
||||
- [X] Interface
|
||||
- [ ] Union
|
||||
- [X] Union
|
||||
- [X] Query
|
||||
- [X] Fields
|
||||
- [X] Arguments
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "async-graphql-derive"
|
||||
version = "0.9.4"
|
||||
version = "0.10.0"
|
||||
authors = ["sunli <scott_s829@163.com>"]
|
||||
edition = "2018"
|
||||
description = "The GraphQL server library implemented by rust"
|
||||
|
|
|
@ -6,6 +6,7 @@ mod input_object;
|
|||
mod interface;
|
||||
mod object;
|
||||
mod output_type;
|
||||
mod union;
|
||||
mod utils;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
|
@ -67,3 +68,17 @@ pub fn Interface(args: TokenStream, input: TokenStream) -> TokenStream {
|
|||
Err(err) => err.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
#[allow(non_snake_case)]
|
||||
pub fn Union(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let interface_args = match args::Interface::parse(parse_macro_input!(args as AttributeArgs)) {
|
||||
Ok(interface_args) => interface_args,
|
||||
Err(err) => return err.to_compile_error().into(),
|
||||
};
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
match union::generate(&interface_args, &input) {
|
||||
Ok(expanded) => expanded,
|
||||
Err(err) => err.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
|
113
async-graphql-derive/src/union.rs
Normal file
113
async-graphql-derive/src/union.rs
Normal file
|
@ -0,0 +1,113 @@
|
|||
use crate::args;
|
||||
use crate::utils::get_crate_name;
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Error, Fields, Result, Type};
|
||||
|
||||
pub fn generate(interface_args: &args::Interface, input: &DeriveInput) -> Result<TokenStream> {
|
||||
let crate_name = get_crate_name(interface_args.internal);
|
||||
let ident = &input.ident;
|
||||
let generics = &input.generics;
|
||||
let attrs = &input.attrs;
|
||||
let vis = &input.vis;
|
||||
let s = match &input.data {
|
||||
Data::Struct(s) => s,
|
||||
_ => return Err(Error::new_spanned(input, "It should be a struct.")),
|
||||
};
|
||||
let fields = match &s.fields {
|
||||
Fields::Unnamed(fields) => fields,
|
||||
_ => return Err(Error::new_spanned(input, "All fields must be unnamed.")),
|
||||
};
|
||||
let mut enum_names = Vec::new();
|
||||
let mut enum_items = Vec::new();
|
||||
let mut type_into_impls = Vec::new();
|
||||
let gql_typename = interface_args
|
||||
.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| ident.to_string());
|
||||
let desc = interface_args
|
||||
.desc
|
||||
.as_ref()
|
||||
.map(|s| quote! {Some(#s)})
|
||||
.unwrap_or_else(|| quote! {None});
|
||||
let mut registry_types = Vec::new();
|
||||
let mut possible_types = Vec::new();
|
||||
let mut inline_fragment_resolvers = Vec::new();
|
||||
|
||||
for field in &fields.unnamed {
|
||||
if let Type::Path(p) = &field.ty {
|
||||
let enum_name = &p.path.segments.last().unwrap().ident;
|
||||
enum_names.push(enum_name);
|
||||
enum_items.push(quote! { #enum_name(#p) });
|
||||
type_into_impls.push(quote! {
|
||||
impl #generics From<#p> for #ident #generics {
|
||||
fn from(obj: #p) -> Self {
|
||||
#ident::#enum_name(obj)
|
||||
}
|
||||
}
|
||||
});
|
||||
registry_types.push(quote! {
|
||||
<#p as #crate_name::GQLType>::create_type_info(registry);
|
||||
});
|
||||
possible_types.push(quote! {
|
||||
<#p as #crate_name::GQLType>::type_name().to_string()
|
||||
});
|
||||
inline_fragment_resolvers.push(quote! {
|
||||
if name == <#p as #crate_name::GQLType>::type_name() {
|
||||
if let #ident::#enum_name(obj) = self {
|
||||
#crate_name::do_resolve(ctx, obj, result).await?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
return Err(Error::new_spanned(field, "Invalid type"));
|
||||
}
|
||||
}
|
||||
|
||||
let expanded = quote! {
|
||||
#(#attrs)*
|
||||
#vis enum #ident #generics { #(#enum_items),* }
|
||||
|
||||
#(#type_into_impls)*
|
||||
|
||||
impl #generics #crate_name::GQLType for #ident #generics {
|
||||
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| {
|
||||
#(#registry_types)*
|
||||
|
||||
#crate_name::registry::Type::Union {
|
||||
name: #gql_typename,
|
||||
description: #desc,
|
||||
possible_types: vec![#(#possible_types),*],
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[#crate_name::async_trait::async_trait]
|
||||
impl #generics #crate_name::GQLObject 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;
|
||||
anyhow::bail!(#crate_name::QueryError::FieldNotFound {
|
||||
field_name: field.name.clone(),
|
||||
object: #gql_typename.to_string(),
|
||||
}
|
||||
.with_position(field.position));
|
||||
}
|
||||
|
||||
async fn resolve_inline_fragment(&self, name: &str, ctx: &#crate_name::ContextSelectionSet<'_>, result: &mut #crate_name::serde_json::Map<String, serde_json::Value>) -> #crate_name::Result<()> {
|
||||
#(#inline_fragment_resolvers)*
|
||||
anyhow::bail!(#crate_name::QueryError::UnrecognizedInlineFragment {
|
||||
object: #gql_typename.to_string(),
|
||||
name: name.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(expanded.into())
|
||||
}
|
|
@ -87,6 +87,9 @@ impl Droid {
|
|||
|
||||
pub struct QueryRoot;
|
||||
|
||||
#[async_graphql::Union]
|
||||
struct HumanDroid(Human, Droid);
|
||||
|
||||
#[async_graphql::Object]
|
||||
impl QueryRoot {
|
||||
#[field]
|
||||
|
@ -105,6 +108,11 @@ impl QueryRoot {
|
|||
}
|
||||
}
|
||||
|
||||
#[field]
|
||||
async fn test(&self, ctx: &Context<'_>) -> HumanDroid {
|
||||
Human(ctx.data::<StarWars>().luke).into()
|
||||
}
|
||||
|
||||
#[field]
|
||||
async fn human(
|
||||
&self,
|
||||
|
|
|
@ -73,7 +73,7 @@ pub use serde_json;
|
|||
|
||||
pub mod http;
|
||||
|
||||
pub use async_graphql_derive::{Enum, InputObject, Interface, Object};
|
||||
pub use async_graphql_derive::{Enum, InputObject, Interface, Object, Union};
|
||||
pub use base::{GQLInputObject, GQLInputValue, GQLObject, GQLOutputValue, GQLScalar, GQLType};
|
||||
pub use context::{Context, Variables};
|
||||
pub use error::{ErrorWithPosition, PositionError, QueryError, QueryParseError};
|
||||
|
|
|
@ -171,6 +171,13 @@ impl<'a> __Type<'a> {
|
|||
.map(|ty| __Type::new(self.registry, ty))
|
||||
.collect(),
|
||||
)
|
||||
} else if let TypeDetail::Simple(Type::Union { possible_types, .. }) = &self.detail {
|
||||
Some(
|
||||
possible_types
|
||||
.iter()
|
||||
.map(|ty| __Type::new(self.registry, ty))
|
||||
.collect(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
|
|
@ -41,7 +41,7 @@ pub enum Type {
|
|||
Union {
|
||||
name: &'static str,
|
||||
description: Option<&'static str>,
|
||||
possible_types: Vec<usize>,
|
||||
possible_types: Vec<String>,
|
||||
},
|
||||
Enum {
|
||||
name: &'static str,
|
||||
|
|
|
@ -81,7 +81,7 @@ impl<Query: GQLObject, Mutation: GQLObject> Schema<Query, Mutation> {
|
|||
}
|
||||
|
||||
pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
|
||||
self.data.insert(Box::new(data));
|
||||
self.data.insert(data);
|
||||
self
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user