query root
This commit is contained in:
parent
cb96ba9048
commit
332faa70fa
12
README.md
12
README.md
|
@ -26,6 +26,15 @@
|
|||
* [Cargo package](https://crates.io/crates/async-graphql)
|
||||
* Minimum supported Rust version: 1.39 or later
|
||||
|
||||
## Features
|
||||
|
||||
* Fully support async/await.
|
||||
* Type safety.
|
||||
* Rustfmt friendly (Procedural Macro).
|
||||
* Custom scalar.
|
||||
* Minimal overhead.
|
||||
* Easy integration (hyper, actix_web, tide, rocket ...).
|
||||
|
||||
## Goals
|
||||
|
||||
- [ ] Types
|
||||
|
@ -37,7 +46,7 @@
|
|||
- [X] ID
|
||||
- [X] DateTime
|
||||
- [X] UUID
|
||||
- Complex Types
|
||||
- [X] Complex Types
|
||||
- [X] List
|
||||
- [X] Non-Null
|
||||
- [X] Object
|
||||
|
@ -45,6 +54,7 @@
|
|||
- [X] InputObject
|
||||
- [ ] Interface
|
||||
- [ ] Union
|
||||
- [ ] Generic Types
|
||||
- [ ] Query
|
||||
- [X] Fields
|
||||
- [X] Arguments
|
||||
|
|
|
@ -2,17 +2,27 @@ use syn::{Attribute, AttributeArgs, Error, Meta, NestedMeta, Result, Type};
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct Object {
|
||||
pub internal: bool,
|
||||
pub auto_impl: bool,
|
||||
pub name: Option<String>,
|
||||
pub desc: Option<String>,
|
||||
}
|
||||
|
||||
impl Object {
|
||||
pub fn parse(args: AttributeArgs) -> Result<Self> {
|
||||
let mut internal = false;
|
||||
let mut auto_impl = false;
|
||||
let mut name = None;
|
||||
let mut desc = None;
|
||||
|
||||
for arg in args {
|
||||
match arg {
|
||||
NestedMeta::Meta(Meta::Path(p)) if p.is_ident("internal") => {
|
||||
internal = true;
|
||||
}
|
||||
NestedMeta::Meta(Meta::Path(p)) if p.is_ident("auto_impl") => {
|
||||
auto_impl = true;
|
||||
}
|
||||
NestedMeta::Meta(Meta::NameValue(nv)) => {
|
||||
if nv.path.is_ident("name") {
|
||||
if let syn::Lit::Str(lit) = nv.lit {
|
||||
|
@ -38,7 +48,12 @@ impl Object {
|
|||
}
|
||||
}
|
||||
|
||||
Ok(Self { name, desc })
|
||||
Ok(Self {
|
||||
internal,
|
||||
auto_impl,
|
||||
name,
|
||||
desc,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -54,6 +69,7 @@ pub struct Field {
|
|||
pub name: Option<String>,
|
||||
pub desc: Option<String>,
|
||||
pub is_attr: bool,
|
||||
pub attr_type: Option<Type>,
|
||||
pub arguments: Vec<Argument>,
|
||||
}
|
||||
|
||||
|
@ -63,6 +79,7 @@ impl Field {
|
|||
let mut name = None;
|
||||
let mut desc = None;
|
||||
let mut is_attr = false;
|
||||
let mut attr_type = None;
|
||||
let mut arguments = Vec::new();
|
||||
|
||||
for attr in attrs {
|
||||
|
@ -93,6 +110,19 @@ impl Field {
|
|||
"Attribute 'desc' should be a string.",
|
||||
));
|
||||
}
|
||||
} else if nv.path.is_ident("attr_type") {
|
||||
if let syn::Lit::Str(lit) = &nv.lit {
|
||||
if let Ok(ty) = syn::parse_str::<syn::Type>(&lit.value()) {
|
||||
attr_type = Some(ty);
|
||||
} else {
|
||||
return Err(Error::new_spanned(&lit, "expect type"));
|
||||
}
|
||||
} else {
|
||||
return Err(Error::new_spanned(
|
||||
&nv.lit,
|
||||
"Attribute 'attr_type' should be a string.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
NestedMeta::Meta(Meta::List(ls)) => {
|
||||
|
@ -170,6 +200,7 @@ impl Field {
|
|||
name,
|
||||
desc,
|
||||
is_attr,
|
||||
attr_type,
|
||||
arguments,
|
||||
}))
|
||||
} else {
|
||||
|
@ -180,17 +211,22 @@ impl Field {
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct Enum {
|
||||
pub internal: bool,
|
||||
pub name: Option<String>,
|
||||
pub desc: Option<String>,
|
||||
}
|
||||
|
||||
impl Enum {
|
||||
pub fn parse(args: AttributeArgs) -> Result<Self> {
|
||||
let mut internal = false;
|
||||
let mut name = None;
|
||||
let mut desc = None;
|
||||
|
||||
for arg in args {
|
||||
match arg {
|
||||
NestedMeta::Meta(Meta::Path(p)) if p.is_ident("internal") => {
|
||||
internal = true;
|
||||
}
|
||||
NestedMeta::Meta(Meta::NameValue(nv)) => {
|
||||
if nv.path.is_ident("name") {
|
||||
if let syn::Lit::Str(lit) = nv.lit {
|
||||
|
@ -216,7 +252,11 @@ impl Enum {
|
|||
}
|
||||
}
|
||||
|
||||
Ok(Self { name, desc })
|
||||
Ok(Self {
|
||||
internal,
|
||||
name,
|
||||
desc,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -270,12 +310,14 @@ impl EnumItem {
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct InputField {
|
||||
pub internal: bool,
|
||||
pub name: Option<String>,
|
||||
pub desc: Option<String>,
|
||||
}
|
||||
|
||||
impl InputField {
|
||||
pub fn parse(attrs: &[Attribute]) -> Result<Self> {
|
||||
let mut internal = false;
|
||||
let mut name = None;
|
||||
let mut desc = None;
|
||||
|
||||
|
@ -284,6 +326,9 @@ impl InputField {
|
|||
if let Ok(Meta::List(args)) = attr.parse_meta() {
|
||||
for meta in args.nested {
|
||||
match meta {
|
||||
NestedMeta::Meta(Meta::Path(p)) if p.is_ident("internal") => {
|
||||
internal = true;
|
||||
}
|
||||
NestedMeta::Meta(Meta::NameValue(nv)) => {
|
||||
if nv.path.is_ident("name") {
|
||||
if let syn::Lit::Str(lit) = nv.lit {
|
||||
|
@ -312,6 +357,10 @@ impl InputField {
|
|||
}
|
||||
}
|
||||
|
||||
Ok(Self { name, desc })
|
||||
Ok(Self {
|
||||
internal,
|
||||
name,
|
||||
desc,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,11 @@
|
|||
use crate::args;
|
||||
use crate::utils::get_crate_name;
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Error, Result};
|
||||
|
||||
pub fn generate(enum_args: &args::Enum, input: &DeriveInput) -> Result<TokenStream> {
|
||||
let crate_name = get_crate_name(enum_args.internal);
|
||||
let attrs = &input.attrs;
|
||||
let vis = &input.vis;
|
||||
let ident = &input.ident;
|
||||
|
@ -33,13 +35,13 @@ pub fn generate(enum_args: &args::Enum, input: &DeriveInput) -> Result<TokenStre
|
|||
.name
|
||||
.take()
|
||||
.unwrap_or_else(|| variant.ident.to_string());
|
||||
enum_items.push(variant);
|
||||
enum_items.push(&variant.ident);
|
||||
let desc = match item_args.desc.take() {
|
||||
Some(desc) => quote! { Some(#desc) },
|
||||
None => quote! { None },
|
||||
};
|
||||
items.push(quote! {
|
||||
async_graphql::GQLEnumItem {
|
||||
#crate_name::GQLEnumItem {
|
||||
name: #gql_item_name,
|
||||
desc: #desc,
|
||||
value: #ident::#item_ident,
|
||||
|
@ -49,36 +51,36 @@ pub fn generate(enum_args: &args::Enum, input: &DeriveInput) -> Result<TokenStre
|
|||
|
||||
let expanded = quote! {
|
||||
#(#attrs)*
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
|
||||
#vis enum #ident {
|
||||
#(#enum_items),*
|
||||
}
|
||||
|
||||
impl async_graphql::GQLEnum for #ident {
|
||||
fn items() -> &'static [async_graphql::GQLEnumItem<#ident>] {
|
||||
impl #crate_name::GQLEnum for #ident {
|
||||
fn items() -> &'static [#crate_name::GQLEnumItem<#ident>] {
|
||||
&[#(#items),*]
|
||||
}
|
||||
}
|
||||
|
||||
impl async_graphql::GQLType for #ident {
|
||||
fn type_name() -> String {
|
||||
#gql_typename.to_string()
|
||||
impl #crate_name::GQLType for #ident {
|
||||
fn type_name() -> std::borrow::Cow<'static, str> {
|
||||
std::borrow::Cow::Borrowed(#gql_typename)
|
||||
}
|
||||
}
|
||||
|
||||
impl async_graphql::GQLInputValue for #ident {
|
||||
fn parse(value: async_graphql::Value) -> Result<Self> {
|
||||
Self::parse_enum(value)
|
||||
impl #crate_name::GQLInputValue for #ident {
|
||||
fn parse(value: #crate_name::Value) -> #crate_name::Result<Self> {
|
||||
#crate_name::GQLEnum::parse_enum(value)
|
||||
}
|
||||
|
||||
fn parse_from_json(value: async_graphql::serde_json::Value) -> Result<Self> {
|
||||
Self::parse_json_enum(value)
|
||||
fn parse_from_json(value: #crate_name::serde_json::Value) -> #crate_name::Result<Self> {
|
||||
#crate_name::GQLEnum::parse_json_enum(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_graphql::async_trait::async_trait]
|
||||
impl async_graphql::GQLOutputValue for #ident {
|
||||
async fn resolve(self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
#[#crate_name::async_trait::async_trait]
|
||||
impl #crate_name::GQLOutputValue for #ident {
|
||||
async fn resolve(&self, _: &#crate_name::ContextSelectionSet<'_>) -> #crate_name::Result<serde_json::Value> {
|
||||
self.resolve_enum()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,11 @@
|
|||
use crate::args;
|
||||
use crate::utils::get_crate_name;
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Error, Result};
|
||||
|
||||
pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<TokenStream> {
|
||||
let crate_name = get_crate_name(object_args.internal);
|
||||
let ident = &input.ident;
|
||||
let s = match &input.data {
|
||||
Data::Struct(s) => s,
|
||||
|
@ -25,10 +27,10 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
let ty = &field.ty;
|
||||
let name = field_args.name.unwrap_or_else(|| ident.to_string());
|
||||
get_fields.push(quote! {
|
||||
let #ident:#ty = async_graphql::GQLInputValue::parse(obj.remove(#name).unwrap_or(async_graphql::Value::Null))?;
|
||||
let #ident:#ty = #crate_name::GQLInputValue::parse(obj.remove(#name).unwrap_or(#crate_name::Value::Null))?;
|
||||
});
|
||||
get_json_fields.push(quote! {
|
||||
let #ident:#ty = async_graphql::GQLInputValue::parse_from_json(obj.remove(#name).unwrap_or(async_graphql::serde_json::Value::Null))?;
|
||||
let #ident:#ty = #crate_name::GQLInputValue::parse_from_json(obj.remove(#name).unwrap_or(#crate_name::serde_json::Value::Null))?;
|
||||
});
|
||||
fields.push(ident);
|
||||
}
|
||||
|
@ -36,31 +38,31 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
let expanded = quote! {
|
||||
#input
|
||||
|
||||
impl async_graphql::GQLType for #ident {
|
||||
fn type_name() -> String {
|
||||
#gql_typename.to_string()
|
||||
impl #crate_name::GQLType for #ident {
|
||||
fn type_name() -> std::borrow::Cow<'static, str> {
|
||||
std::borrow::Cow::Borrowed(#gql_typename)
|
||||
}
|
||||
}
|
||||
|
||||
impl async_graphql::GQLInputValue for #ident {
|
||||
fn parse(value: async_graphql::Value) -> async_graphql::Result<Self> {
|
||||
if let async_graphql::Value::Object(mut obj) = value {
|
||||
impl #crate_name::GQLInputValue for #ident {
|
||||
fn parse(value: #crate_name::Value) -> #crate_name::Result<Self> {
|
||||
if let #crate_name::Value::Object(mut obj) = value {
|
||||
#(#get_fields)*
|
||||
Ok(Self { #(#fields),* })
|
||||
} else {
|
||||
Err(async_graphql::QueryError::ExpectedType {
|
||||
Err(#crate_name::QueryError::ExpectedType {
|
||||
expect: Self::type_name(),
|
||||
actual: value,
|
||||
}.into())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: async_graphql::serde_json::Value) -> async_graphql::Result<Self> {
|
||||
if let async_graphql::serde_json::Value::Object(mut obj) = value {
|
||||
fn parse_from_json(value: #crate_name::serde_json::Value) -> #crate_name::Result<Self> {
|
||||
if let #crate_name::serde_json::Value::Object(mut obj) = value {
|
||||
#(#get_json_fields)*
|
||||
Ok(Self { #(#fields),* })
|
||||
} else {
|
||||
Err(async_graphql::QueryError::ExpectedJsonType {
|
||||
Err(#crate_name::QueryError::ExpectedJsonType {
|
||||
expect: Self::type_name(),
|
||||
actual: value,
|
||||
}.into())
|
||||
|
@ -68,8 +70,7 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
}
|
||||
}
|
||||
|
||||
impl async_graphql::GQLInputObject for #ident {}
|
||||
impl #crate_name::GQLInputObject for #ident {}
|
||||
};
|
||||
println!("{}", expanded.to_string());
|
||||
Ok(expanded.into())
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@ mod args;
|
|||
mod r#enum;
|
||||
mod input_object;
|
||||
mod object;
|
||||
mod utils;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use syn::parse_macro_input;
|
||||
|
|
|
@ -1,10 +1,12 @@
|
|||
use crate::args;
|
||||
use crate::utils::get_crate_name;
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Span;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Error, Ident, Result};
|
||||
|
||||
pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<TokenStream> {
|
||||
let crate_name = get_crate_name(object_args.internal);
|
||||
let attrs = &input.attrs;
|
||||
let vis = &input.vis;
|
||||
let ident = &input.ident;
|
||||
|
@ -18,9 +20,11 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
.clone()
|
||||
.unwrap_or_else(|| ident.to_string());
|
||||
let trait_ident = Ident::new(&format!("{}Fields", ident.to_string()), Span::call_site());
|
||||
let mut new_fields = Vec::new();
|
||||
let mut obj_attrs = Vec::new();
|
||||
let mut obj_fields = Vec::new();
|
||||
let mut trait_fns = Vec::new();
|
||||
let mut resolvers = Vec::new();
|
||||
let mut all_is_simple_attr = true;
|
||||
|
||||
for field in &s.fields {
|
||||
if let Some(field_args) = args::Field::parse(&field.attrs)? {
|
||||
|
@ -30,8 +34,15 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
let ident = field.ident.as_ref().unwrap();
|
||||
let field_name = ident.to_string();
|
||||
|
||||
obj_fields.push(field);
|
||||
if field_args.is_attr {
|
||||
new_fields.push(quote! { #vis #ident: #ty });
|
||||
let ty = field_args.attr_type.as_ref().unwrap_or(ty);
|
||||
obj_attrs.push(quote! { #vis #ident: #ty });
|
||||
if !field_args.arguments.is_empty() || field_args.attr_type.is_some() {
|
||||
all_is_simple_attr = false;
|
||||
}
|
||||
} else {
|
||||
all_is_simple_attr = false;
|
||||
}
|
||||
|
||||
let mut decl_params = Vec::new();
|
||||
|
@ -51,13 +62,13 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
}
|
||||
|
||||
trait_fns.push(quote! {
|
||||
async fn #ident(&self, ctx: &async_graphql::ContextField<'_>, #(#decl_params),*) -> async_graphql::Result<#ty>;
|
||||
async fn #ident(&self, ctx: &#crate_name::ContextField<'_>, #(#decl_params),*) -> #crate_name::Result<#ty>;
|
||||
});
|
||||
|
||||
resolvers.push(quote! {
|
||||
if field.name.as_str() == #field_name {
|
||||
#(#get_params)*
|
||||
let obj = #trait_ident::#ident(&self, &ctx_field, #(#use_params),*).await.
|
||||
let obj = #trait_ident::#ident(self, &ctx_field, #(#use_params),*).await.
|
||||
map_err(|err| err.with_position(field.position))?;
|
||||
let ctx_obj = ctx_field.with_item(&field.selection_set);
|
||||
let value = obj.resolve(&ctx_obj).await.
|
||||
|
@ -68,42 +79,62 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
}
|
||||
});
|
||||
} else {
|
||||
new_fields.push(quote! { #field });
|
||||
obj_attrs.push(quote! { #field });
|
||||
}
|
||||
}
|
||||
|
||||
let mut impl_fields = quote! {};
|
||||
if object_args.auto_impl && all_is_simple_attr {
|
||||
let mut impl_fns = Vec::new();
|
||||
for field in obj_fields {
|
||||
let ident = &field.ident;
|
||||
let ty = &field.ty;
|
||||
impl_fns.push(quote! {
|
||||
async fn #ident(&self, _: &#crate_name::ContextField<'_>) -> #crate_name::Result<#ty> {
|
||||
Ok(self.#ident.clone())
|
||||
}
|
||||
});
|
||||
}
|
||||
impl_fields = quote! {
|
||||
#[#crate_name::async_trait::async_trait]
|
||||
impl #trait_ident for #ident {
|
||||
#(#impl_fns)*
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let expanded = quote! {
|
||||
#(#attrs)*
|
||||
#vis struct #ident {
|
||||
#(#new_fields),*
|
||||
#(#obj_attrs),*
|
||||
}
|
||||
|
||||
#[async_graphql::async_trait::async_trait]
|
||||
#[#crate_name::async_trait::async_trait]
|
||||
#vis trait #trait_ident {
|
||||
#(#trait_fns)*
|
||||
}
|
||||
|
||||
impl async_graphql::GQLType for #ident {
|
||||
fn type_name() -> String {
|
||||
#gql_typename.to_string()
|
||||
impl #crate_name::GQLType for #ident {
|
||||
fn type_name() -> std::borrow::Cow<'static, str> {
|
||||
std::borrow::Cow::Borrowed(#gql_typename)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_graphql::async_trait::async_trait]
|
||||
impl async_graphql::GQLOutputValue for #ident {
|
||||
async fn resolve(self, ctx: &async_graphql::ContextSelectionSet<'_>) -> async_graphql::Result<async_graphql::serde_json::Value> {
|
||||
use async_graphql::ErrorWithPosition;
|
||||
#[#crate_name::async_trait::async_trait]
|
||||
impl #crate_name::GQLOutputValue for #ident {
|
||||
async fn resolve(&self, ctx: &#crate_name::ContextSelectionSet<'_>) -> #crate_name::Result<#crate_name::serde_json::Value> {
|
||||
use #crate_name::ErrorWithPosition;
|
||||
|
||||
if ctx.items.is_empty() {
|
||||
async_graphql::anyhow::bail!(async_graphql::QueryError::MustHaveSubFields {
|
||||
#crate_name::anyhow::bail!(#crate_name::QueryError::MustHaveSubFields {
|
||||
object: #gql_typename,
|
||||
}.with_position(ctx.span.0));
|
||||
}
|
||||
|
||||
let mut result = async_graphql::serde_json::Map::<String, async_graphql::serde_json::Value>::new();
|
||||
let mut result = #crate_name::serde_json::Map::<String, #crate_name::serde_json::Value>::new();
|
||||
for selection in &ctx.items {
|
||||
match selection {
|
||||
async_graphql::graphql_parser::query::Selection::Field(field) => {
|
||||
#crate_name::graphql_parser::query::Selection::Field(field) => {
|
||||
let ctx_field = ctx.with_item(field);
|
||||
if field.name.as_str() == "__typename" {
|
||||
let name = field.alias.clone().unwrap_or_else(|| field.name.clone());
|
||||
|
@ -111,7 +142,7 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
continue;
|
||||
}
|
||||
#(#resolvers)*
|
||||
async_graphql::anyhow::bail!(async_graphql::QueryError::FieldNotFound {
|
||||
#crate_name::anyhow::bail!(#crate_name::QueryError::FieldNotFound {
|
||||
field_name: field.name.clone(),
|
||||
object: #gql_typename,
|
||||
}.with_position(field.position));
|
||||
|
@ -120,11 +151,13 @@ pub fn generate(object_args: &args::Object, input: &DeriveInput) -> Result<Token
|
|||
}
|
||||
}
|
||||
|
||||
Ok(async_graphql::serde_json::Value::Object(result))
|
||||
Ok(#crate_name::serde_json::Value::Object(result))
|
||||
}
|
||||
}
|
||||
|
||||
impl async_graphql::GQLObject for #ident {}
|
||||
impl #crate_name::GQLObject for #ident {}
|
||||
|
||||
#impl_fields
|
||||
};
|
||||
Ok(expanded.into())
|
||||
}
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::quote;
|
||||
use syn::Ident;
|
||||
|
||||
pub fn get_crate_name(internal: bool) -> TokenStream {
|
||||
match internal {
|
||||
true => quote! { crate },
|
||||
false => {
|
||||
let id = Ident::new("async_graphql", Span::call_site());
|
||||
quote! { #id }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -12,6 +12,15 @@ struct MyInputObj {
|
|||
b: i32,
|
||||
}
|
||||
|
||||
#[async_graphql::Object(auto_impl)]
|
||||
struct MyObj2 {
|
||||
#[field(attr)]
|
||||
a: i32,
|
||||
|
||||
#[field(attr)]
|
||||
b: i32,
|
||||
}
|
||||
|
||||
#[async_graphql::Object(name = "haha", desc = "hehe")]
|
||||
struct MyObj {
|
||||
#[field(
|
||||
|
@ -31,6 +40,15 @@ struct MyObj {
|
|||
#[field(arg(name = "input", type = "MyInputObj"))]
|
||||
d: i32,
|
||||
|
||||
#[field]
|
||||
e: &'static str,
|
||||
|
||||
#[field]
|
||||
f: &'static [i32],
|
||||
|
||||
#[field]
|
||||
g: &'static MyObj2,
|
||||
|
||||
#[field]
|
||||
child: ChildObj,
|
||||
}
|
||||
|
@ -59,6 +77,18 @@ impl MyObjFields for MyObj {
|
|||
Ok(input.a + input.b)
|
||||
}
|
||||
|
||||
async fn e(&self, ctx: &ContextField<'_>) -> Result<&'static str> {
|
||||
Ok("hehehe")
|
||||
}
|
||||
|
||||
async fn f(&self, ctx: &ContextField<'_>) -> Result<&'static [i32]> {
|
||||
Ok(&[1, 2, 3, 4, 5])
|
||||
}
|
||||
|
||||
async fn g(&self, ctx: &ContextField<'_>) -> Result<&'static MyObj2> {
|
||||
Ok(&MyObj2 { a: 10, b: 20 })
|
||||
}
|
||||
|
||||
async fn child(&self, ctx: &ContextField<'_>) -> async_graphql::Result<ChildObj> {
|
||||
Ok(ChildObj { value: 10.0 })
|
||||
}
|
||||
|
@ -76,7 +106,7 @@ async fn main() {
|
|||
let res = QueryBuilder::new(
|
||||
MyObj { a: 10 },
|
||||
GQLEmptyMutation,
|
||||
"{ b c(input:B) d(input:{a:10 b:20}) }",
|
||||
"{ b c(input:B) d(input:{a:10 b:20}) e f g { a b } }",
|
||||
)
|
||||
.execute()
|
||||
.await
|
||||
|
|
15
src/error.rs
15
src/error.rs
|
@ -1,6 +1,7 @@
|
|||
use crate::Error;
|
||||
use graphql_parser::query::Value;
|
||||
use graphql_parser::Pos;
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
|
@ -13,11 +14,14 @@ pub enum QueryError {
|
|||
NotSupported,
|
||||
|
||||
#[error("Expected type \"{expect}\", found {actual}.")]
|
||||
ExpectedType { expect: String, actual: Value },
|
||||
ExpectedType {
|
||||
expect: Cow<'static, str>,
|
||||
actual: Value,
|
||||
},
|
||||
|
||||
#[error("Expected type \"{expect}\", found {actual}.")]
|
||||
ExpectedJsonType {
|
||||
expect: String,
|
||||
expect: Cow<'static, str>,
|
||||
actual: serde_json::Value,
|
||||
},
|
||||
|
||||
|
@ -36,8 +40,11 @@ pub enum QueryError {
|
|||
#[error("Schema is not configured for mutations.")]
|
||||
NotConfiguredMutations,
|
||||
|
||||
#[error("Invalid value for enum \"{enum_type}\".")]
|
||||
InvalidEnumValue { enum_type: String, value: String },
|
||||
#[error("Invalid value for enum \"{ty}\".")]
|
||||
InvalidEnumValue {
|
||||
ty: Cow<'static, str>,
|
||||
value: String,
|
||||
},
|
||||
|
||||
#[error("Required field \"{field_name}\" for InputObject \"{object}\" does not exist.")]
|
||||
RequiredField {
|
||||
|
|
25
src/lib.rs
25
src/lib.rs
|
@ -34,17 +34,13 @@
|
|||
extern crate thiserror;
|
||||
|
||||
mod context;
|
||||
mod r#enum;
|
||||
mod error;
|
||||
mod id;
|
||||
mod query;
|
||||
mod scalar;
|
||||
mod scalars;
|
||||
mod schema;
|
||||
mod r#type;
|
||||
|
||||
#[cfg(feature = "chrono")]
|
||||
mod datetime;
|
||||
#[cfg(feature = "uuid")]
|
||||
mod uuid;
|
||||
mod types;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use anyhow;
|
||||
|
@ -59,19 +55,18 @@ pub use async_graphql_derive::{Enum, InputObject, Object};
|
|||
pub use context::{Context, ContextField, Data, Variables};
|
||||
pub use error::{ErrorWithPosition, PositionError, QueryError, QueryParseError};
|
||||
pub use graphql_parser::query::Value;
|
||||
pub use id::ID;
|
||||
pub use query::QueryBuilder;
|
||||
pub use scalar::Scalar;
|
||||
pub use scalars::ID;
|
||||
pub use types::GQLEmptyMutation;
|
||||
|
||||
pub type Result<T> = anyhow::Result<T>;
|
||||
pub type Error = anyhow::Error;
|
||||
|
||||
// internal types
|
||||
#[doc(hidden)]
|
||||
pub use context::ContextSelectionSet;
|
||||
#[doc(hidden)]
|
||||
pub use r#enum::{GQLEnum, GQLEnumItem};
|
||||
pub use r#type::{GQLInputObject, GQLInputValue, GQLObject, GQLOutputValue, GQLType};
|
||||
#[doc(hidden)]
|
||||
pub use r#type::{
|
||||
GQLEmptyMutation, GQLInputObject, GQLInputValue, GQLObject, GQLOutputValue, GQLType,
|
||||
};
|
||||
|
||||
pub type Result<T> = anyhow::Result<T>;
|
||||
pub type Error = anyhow::Error;
|
||||
pub use types::{GQLEnum, GQLEnumItem};
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
use crate::{
|
||||
Context, Data, ErrorWithPosition, GQLObject, QueryError, QueryParseError, Result,
|
||||
Variables,
|
||||
Context, Data, ErrorWithPosition, GQLObject, QueryError, QueryParseError, Result, Variables,
|
||||
};
|
||||
use graphql_parser::parse_query;
|
||||
use graphql_parser::query::{Definition, OperationDefinition};
|
||||
|
|
177
src/scalar.rs
177
src/scalar.rs
|
@ -1,17 +1,18 @@
|
|||
use crate::r#type::{GQLInputValue, GQLOutputValue, GQLType};
|
||||
use crate::{ContextSelectionSet, QueryError, Result};
|
||||
use crate::{ContextSelectionSet, Result};
|
||||
use graphql_parser::query::Value;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub trait Scalar: Sized + Send {
|
||||
fn type_name() -> &'static str;
|
||||
fn parse(value: Value) -> Result<Self>;
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self>;
|
||||
fn into_json(self) -> Result<serde_json::Value>;
|
||||
fn to_json(&self) -> Result<serde_json::Value>;
|
||||
}
|
||||
|
||||
impl<T: Scalar> GQLType for T {
|
||||
fn type_name() -> String {
|
||||
T::type_name().to_string()
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Borrowed(T::type_name())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -26,170 +27,8 @@ impl<T: Scalar> GQLInputValue for T {
|
|||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: Scalar> GQLOutputValue for T {
|
||||
async fn resolve(self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
T::into_json(self)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_integer_scalars {
|
||||
($($ty:ty),*) => {
|
||||
$(
|
||||
impl Scalar for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
"Int!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Int(n) => Ok(n.as_i64().unwrap() as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: <Self as Scalar>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Number(n) if n.is_i64() => Ok(n.as_i64().unwrap() as Self),
|
||||
serde_json::Value::Number(n) => Ok(n.as_f64().unwrap() as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
Ok(self.into())
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_integer_scalars!(i8, i16, i32, i64, u8, u16, u32, u64);
|
||||
|
||||
macro_rules! impl_float_scalars {
|
||||
($($ty:ty),*) => {
|
||||
$(
|
||||
impl Scalar for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
"Float!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Int(n) => Ok(n.as_i64().unwrap() as Self),
|
||||
Value::Float(n) => Ok(n as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: <Self as Scalar>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Number(n) => Ok(n.as_f64().unwrap() as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
Ok(self.into())
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_float_scalars!(f32, f64);
|
||||
|
||||
impl Scalar for String {
|
||||
fn type_name() -> &'static str {
|
||||
"String!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: <Self as GQLType>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::String(s) => Ok(s),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
Ok(self.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Scalar for bool {
|
||||
fn type_name() -> &'static str {
|
||||
"Boolean!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Boolean(n) => Ok(n),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: <Self as GQLType>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Bool(n) => Ok(n),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name().to_string(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
Ok(self.into())
|
||||
impl<T: Scalar + Sync> GQLOutputValue for T {
|
||||
async fn resolve(&self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
T::to_json(self)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
use crate::{GQLType, QueryError, Result, Scalar, Value};
|
||||
|
||||
impl Scalar for bool {
|
||||
fn type_name() -> &'static str {
|
||||
"Boolean!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Boolean(n) => Ok(n),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: <Self as GQLType>::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Bool(n) => Ok(n),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok((*self).into())
|
||||
}
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
use crate::{QueryError, Result, Scalar, Value};
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl Scalar for DateTime<Utc> {
|
||||
fn type_name() -> &'static str {
|
||||
|
@ -11,7 +12,7 @@ impl Scalar for DateTime<Utc> {
|
|||
Value::String(s) => Ok(Utc.datetime_from_str(&s, "%+")?),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Self::type_name().to_string(),
|
||||
expect: Cow::Borrowed(Self::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
|
@ -24,7 +25,7 @@ impl Scalar for DateTime<Utc> {
|
|||
serde_json::Value::String(s) => Ok(Utc.datetime_from_str(&s, "%+")?),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: Self::type_name().to_string(),
|
||||
expect: Cow::Borrowed(Self::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
|
@ -32,7 +33,7 @@ impl Scalar for DateTime<Utc> {
|
|||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok(self.to_rfc3339().into())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
use crate::{GQLType, QueryError, Result, Scalar, Value};
|
||||
use std::borrow::Cow;
|
||||
|
||||
macro_rules! impl_float_scalars {
|
||||
($($ty:ty),*) => {
|
||||
$(
|
||||
impl Scalar for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
"Float!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Int(n) => Ok(n.as_i64().unwrap() as Self),
|
||||
Value::Float(n) => Ok(n as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Cow::Borrowed(<Self as Scalar>::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Number(n) => Ok(n.as_f64().unwrap() as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok((*self).into())
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_float_scalars!(f32, f64);
|
|
@ -1,4 +1,5 @@
|
|||
use crate::{QueryError, Result, Scalar, Value};
|
||||
use std::borrow::Cow;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
|
||||
|
@ -29,7 +30,7 @@ impl Scalar for ID {
|
|||
Value::String(s) => Ok(ID(s)),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Self::type_name().to_string(),
|
||||
expect: Cow::Borrowed(Self::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
|
@ -43,7 +44,7 @@ impl Scalar for ID {
|
|||
serde_json::Value::String(s) => Ok(ID(s)),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: Self::type_name().to_string(),
|
||||
expect: Cow::Borrowed(Self::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
|
@ -51,7 +52,7 @@ impl Scalar for ID {
|
|||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok(self.0.clone().into())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
use crate::{GQLType, QueryError, Result, Scalar, Value};
|
||||
use std::borrow::Cow;
|
||||
|
||||
macro_rules! impl_integer_scalars {
|
||||
($($ty:ty),*) => {
|
||||
$(
|
||||
impl Scalar for $ty {
|
||||
fn type_name() -> &'static str {
|
||||
"Int!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Int(n) => Ok(n.as_i64().unwrap() as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Cow::Borrowed(<Self as Scalar>::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Number(n) if n.is_i64() => Ok(n.as_i64().unwrap() as Self),
|
||||
serde_json::Value::Number(n) => Ok(n.as_f64().unwrap() as Self),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok((*self).into())
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_integer_scalars!(i8, i16, i32, i64, u8, u16, u32, u64);
|
|
@ -0,0 +1,12 @@
|
|||
mod bool;
|
||||
mod floats;
|
||||
mod id;
|
||||
mod integers;
|
||||
mod string;
|
||||
|
||||
#[cfg(feature = "chrono")]
|
||||
mod datetime;
|
||||
#[cfg(feature = "uuid")]
|
||||
mod uuid;
|
||||
|
||||
pub use id::ID;
|
|
@ -0,0 +1,51 @@
|
|||
use crate::{ContextSelectionSet, GQLOutputValue, GQLType, QueryError, Result, Scalar, Value};
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl Scalar for String {
|
||||
fn type_name() -> &'static str {
|
||||
"String!"
|
||||
}
|
||||
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: <Self as GQLType>::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::String(s) => Ok(s),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: <Self as GQLType>::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok(self.clone().into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> GQLType for &'a str {
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Borrowed("String!")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<'a> GQLOutputValue for &'a str {
|
||||
async fn resolve(&self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
Ok(self.to_string().into())
|
||||
}
|
||||
}
|
|
@ -1,4 +1,5 @@
|
|||
use crate::{QueryError, Result, Scalar, Value};
|
||||
use std::borrow::Cow;
|
||||
use uuid::Uuid;
|
||||
|
||||
impl Scalar for Uuid {
|
||||
|
@ -11,7 +12,7 @@ impl Scalar for Uuid {
|
|||
Value::String(s) => Ok(Uuid::parse_str(&s)?),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Self::type_name().to_string(),
|
||||
expect: Cow::Borrowed(Self::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
|
@ -24,7 +25,7 @@ impl Scalar for Uuid {
|
|||
serde_json::Value::String(s) => Ok(Uuid::parse_str(&s)?),
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: Self::type_name().to_string(),
|
||||
expect: Cow::Borrowed(Self::type_name()),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
|
@ -32,7 +33,7 @@ impl Scalar for Uuid {
|
|||
}
|
||||
}
|
||||
|
||||
fn into_json(self) -> Result<serde_json::Value> {
|
||||
fn to_json(&self) -> Result<serde_json::Value> {
|
||||
Ok(self.to_string().into())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
use crate::schema::{__InputValue, __Type};
|
||||
use async_graphql_derive::Object;
|
||||
|
||||
#[Object(internal, auto_impl)]
|
||||
pub struct __Field {
|
||||
#[field(attr)]
|
||||
name: &'static str,
|
||||
|
||||
#[field(attr)]
|
||||
description: Option<&'static str>,
|
||||
|
||||
#[field(attr)]
|
||||
args: &'static [__InputValue],
|
||||
|
||||
#[field(attr, name = "type")]
|
||||
ty: &'static __Type,
|
||||
|
||||
#[field(attr, name = "isDeprecated")]
|
||||
is_deprecated: bool,
|
||||
|
||||
#[field(attr, name = "deprecationReason")]
|
||||
deprecation_reason: Option<String>,
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
use crate::schema::__Type;
|
||||
use crate::Value;
|
||||
use async_graphql_derive::Object;
|
||||
|
||||
#[Object(internal)]
|
||||
pub struct __InputValue {
|
||||
#[field(attr)]
|
||||
name: &'static str,
|
||||
|
||||
#[field(attr)]
|
||||
description: Option<&'static str>,
|
||||
|
||||
#[field(attr, name = "type")]
|
||||
ty: &'static __Type,
|
||||
|
||||
#[field(attr, attr_type = "Value", name = "defaultValue")]
|
||||
default_value: String,
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
use async_graphql_derive::Enum;
|
||||
|
||||
#[Enum(internal)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum __TypeKind {
|
||||
#[item(desc = "Indicates this type is a scalar.")]
|
||||
SCALAR,
|
||||
|
||||
#[item(desc = "Indicates this type is an object. `fields` and `interfaces` are valid fields.")]
|
||||
OBJECT,
|
||||
|
||||
#[item(
|
||||
desc = "Indicates this type is an interface. `fields` and `possibleTypes` are valid fields."
|
||||
)]
|
||||
INTERFACE,
|
||||
|
||||
#[item(desc = "Indicates this type is a union. `possibleTypes` is a valid field.")]
|
||||
UNION,
|
||||
|
||||
#[item(desc = "Indicates this type is an enum. `enumValues` is a valid field.")]
|
||||
ENUM,
|
||||
|
||||
#[item(desc = "Indicates this type is an input object. `inputFields` is a valid field.")]
|
||||
INPUT_OBJECT,
|
||||
|
||||
#[item(desc = "Indicates this type is a list. `ofType` is a valid field.")]
|
||||
LIST,
|
||||
|
||||
#[item(desc = "Indicates this type is a non-null. `ofType` is a valid field.")]
|
||||
NON_NULL,
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
mod field;
|
||||
mod input_value;
|
||||
mod kind;
|
||||
mod r#type;
|
||||
|
||||
pub use field::__Field;
|
||||
pub use input_value::__InputValue;
|
||||
pub use kind::__TypeKind;
|
||||
pub use r#type::__Type;
|
|
@ -0,0 +1,36 @@
|
|||
use crate::schema::{__Field, __InputValue, __TypeKind};
|
||||
use async_graphql_derive::Object;
|
||||
|
||||
#[Object(internal)]
|
||||
pub struct __Type {
|
||||
#[field(attr)]
|
||||
kind: __TypeKind,
|
||||
|
||||
#[field(attr)]
|
||||
name: Option<&'static str>,
|
||||
|
||||
#[field(attr)]
|
||||
description: Option<&'static str>,
|
||||
|
||||
#[field(attr, arg(name = "includeDeprecated", type = "bool"))]
|
||||
fields: Option<&'static [__Field]>,
|
||||
|
||||
#[field(attr)]
|
||||
interfaces: Option<&'static [__Type]>,
|
||||
|
||||
#[field(attr, name = "possibleTypes")]
|
||||
possible_types: Option<&'static [__Type]>,
|
||||
|
||||
#[field(
|
||||
attr,
|
||||
name = "enumValues",
|
||||
arg(name = "includeDeprecated", type = "bool")
|
||||
)]
|
||||
enum_values: Option<&'static [__Type]>,
|
||||
|
||||
#[field(attr, name = "inputFields")]
|
||||
input_fields: Option<&'static [__InputValue]>,
|
||||
|
||||
#[field(attr, name = "ofType")]
|
||||
of_type: Option<&'static __Type>,
|
||||
}
|
114
src/type.rs
114
src/type.rs
|
@ -1,9 +1,10 @@
|
|||
use crate::{ContextSelectionSet, ErrorWithPosition, QueryError, Result};
|
||||
use crate::{ContextSelectionSet, Result};
|
||||
use graphql_parser::query::Value;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait GQLType {
|
||||
fn type_name() -> String;
|
||||
fn type_name() -> Cow<'static, str>;
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
|
@ -15,118 +16,11 @@ pub trait GQLInputValue: GQLType + Sized {
|
|||
#[doc(hidden)]
|
||||
#[async_trait::async_trait]
|
||||
pub trait GQLOutputValue: GQLType {
|
||||
async fn resolve(self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value>;
|
||||
}
|
||||
|
||||
impl<T: GQLType> GQLType for Vec<T> {
|
||||
fn type_name() -> String {
|
||||
format!("[{}]!", T::type_name()).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GQLInputValue> GQLInputValue for Vec<T> {
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::List(values) => {
|
||||
let mut result = Vec::new();
|
||||
for value in values {
|
||||
result.push(GQLInputValue::parse(value)?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Self::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Array(values) => {
|
||||
let mut result = Vec::new();
|
||||
for value in values {
|
||||
result.push(GQLInputValue::parse_from_json(value)?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: Self::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: GQLOutputValue + Send> GQLOutputValue for Vec<T> {
|
||||
async fn resolve(self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
let mut res = Vec::new();
|
||||
for item in self {
|
||||
res.push(item.resolve(ctx).await?);
|
||||
}
|
||||
Ok(res.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GQLType> GQLType for Option<T> {
|
||||
fn type_name() -> String {
|
||||
format!("{}", T::type_name().trim_end_matches("!")).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GQLInputValue> GQLInputValue for Option<T> {
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Null => Ok(None),
|
||||
_ => Ok(Some(GQLInputValue::parse(value)?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Null => Ok(None),
|
||||
_ => Ok(Some(GQLInputValue::parse_from_json(value)?)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: GQLOutputValue + Send> GQLOutputValue for Option<T> {
|
||||
async fn resolve(self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
if let Some(inner) = self {
|
||||
inner.resolve(ctx).await
|
||||
} else {
|
||||
Ok(serde_json::Value::Null)
|
||||
}
|
||||
}
|
||||
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value>;
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait GQLObject: GQLOutputValue {}
|
||||
|
||||
pub struct GQLEmptyMutation;
|
||||
|
||||
impl GQLType for GQLEmptyMutation {
|
||||
fn type_name() -> String {
|
||||
"EmptyMutation".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl GQLOutputValue for GQLEmptyMutation {
|
||||
async fn resolve(self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
anyhow::bail!(QueryError::NotConfiguredMutations.with_position(ctx.item.span.0));
|
||||
}
|
||||
}
|
||||
|
||||
impl GQLObject for GQLEmptyMutation {}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait GQLInputObject: GQLInputValue {}
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
use crate::{
|
||||
ContextSelectionSet, ErrorWithPosition, GQLObject, GQLOutputValue, GQLType, QueryError, Result,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub struct GQLEmptyMutation;
|
||||
|
||||
impl GQLType for GQLEmptyMutation {
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Borrowed("EmptyMutation")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl GQLOutputValue for GQLEmptyMutation {
|
||||
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
anyhow::bail!(QueryError::NotConfiguredMutations.with_position(ctx.item.span.0));
|
||||
}
|
||||
}
|
||||
|
||||
impl GQLObject for GQLEmptyMutation {}
|
|
@ -23,7 +23,7 @@ pub trait GQLEnum: GQLType + Sized + Eq + Send + Copy + Sized + 'static {
|
|||
}
|
||||
}
|
||||
Err(QueryError::InvalidEnumValue {
|
||||
enum_type: Self::type_name(),
|
||||
ty: Self::type_name(),
|
||||
value: s,
|
||||
}
|
||||
.into())
|
||||
|
@ -48,7 +48,7 @@ pub trait GQLEnum: GQLType + Sized + Eq + Send + Copy + Sized + 'static {
|
|||
}
|
||||
}
|
||||
Err(QueryError::InvalidEnumValue {
|
||||
enum_type: Self::type_name(),
|
||||
ty: Self::type_name(),
|
||||
value: s,
|
||||
}
|
||||
.into())
|
||||
|
@ -63,10 +63,10 @@ pub trait GQLEnum: GQLType + Sized + Eq + Send + Copy + Sized + 'static {
|
|||
}
|
||||
}
|
||||
|
||||
fn resolve_enum(self) -> Result<serde_json::Value> {
|
||||
fn resolve_enum(&self) -> Result<serde_json::Value> {
|
||||
let items = Self::items();
|
||||
for item in items {
|
||||
if item.value == self {
|
||||
if item.value == *self {
|
||||
return Ok(item.name.clone().into());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
use crate::{
|
||||
ContextSelectionSet, GQLInputValue, GQLOutputValue, GQLType, QueryError, Result, Value,
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl<T: GQLType> GQLType for Vec<T> {
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Owned(format!("[{}]!", T::type_name()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GQLInputValue> GQLInputValue for Vec<T> {
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::List(values) => {
|
||||
let mut result = Vec::new();
|
||||
for value in values {
|
||||
result.push(GQLInputValue::parse(value)?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedType {
|
||||
expect: Self::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Array(values) => {
|
||||
let mut result = Vec::new();
|
||||
for value in values {
|
||||
result.push(GQLInputValue::parse_from_json(value)?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
return Err(QueryError::ExpectedJsonType {
|
||||
expect: Self::type_name(),
|
||||
actual: value,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: GQLOutputValue + Send + Sync> GQLOutputValue for Vec<T> {
|
||||
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
let mut res = Vec::new();
|
||||
for item in self {
|
||||
res.push(item.resolve(ctx).await?);
|
||||
}
|
||||
Ok(res.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GQLType> GQLType for &[T] {
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Owned(format!("[{}]!", T::type_name()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: GQLOutputValue + Send + Sync> GQLOutputValue for &[T] {
|
||||
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
let mut res = Vec::new();
|
||||
for item in self.iter() {
|
||||
res.push(item.resolve(ctx).await?);
|
||||
}
|
||||
Ok(res.into())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
mod empty_mutation;
|
||||
mod r#enum;
|
||||
mod list;
|
||||
mod non_null;
|
||||
mod query_root;
|
||||
|
||||
pub use empty_mutation::GQLEmptyMutation;
|
||||
pub use r#enum::{GQLEnum, GQLEnumItem};
|
|
@ -0,0 +1,35 @@
|
|||
use crate::{ContextSelectionSet, GQLInputValue, GQLOutputValue, GQLType, Result, Value};
|
||||
use std::borrow::Cow;
|
||||
|
||||
impl<T: GQLType> GQLType for Option<T> {
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Owned(format!("{}", T::type_name().trim_end_matches("!")))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GQLInputValue> GQLInputValue for Option<T> {
|
||||
fn parse(value: Value) -> Result<Self> {
|
||||
match value {
|
||||
Value::Null => Ok(None),
|
||||
_ => Ok(Some(GQLInputValue::parse(value)?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
|
||||
match value {
|
||||
serde_json::Value::Null => Ok(None),
|
||||
_ => Ok(Some(GQLInputValue::parse_from_json(value)?)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: GQLOutputValue + Send + Sync> GQLOutputValue for Option<T> {
|
||||
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
if let Some(inner) = self {
|
||||
inner.resolve(ctx).await
|
||||
} else {
|
||||
Ok(serde_json::Value::Null)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
use crate::{ContextSelectionSet, GQLOutputValue, GQLType, Result};
|
||||
use graphql_parser::query::Selection;
|
||||
use std::borrow::Cow;
|
||||
|
||||
struct QueryRoot<T>(T);
|
||||
|
||||
impl<T> GQLType for QueryRoot<T> {
|
||||
fn type_name() -> Cow<'static, str> {
|
||||
Cow::Borrowed("Root")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T: GQLOutputValue + Send + Sync> GQLOutputValue for QueryRoot<T> {
|
||||
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
|
||||
let mut value = self.0.resolve(ctx).await?;
|
||||
if let serde_json::Value::Object(obj) = &mut value {
|
||||
for item in &ctx.item.items {
|
||||
if let Selection::Field(field) = item {
|
||||
if field.name == "__schema" {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue