Allow specifying the Context type in #[derive(GraphQLObject)]

This commit extends the GraphQLObject derive to allow specifying a
custom context type.
This commit is contained in:
Christoph Herzog 2019-03-06 20:05:46 +01:00
parent 6562440105
commit 8c5b86e1c6
2 changed files with 17 additions and 1 deletions

View file

@ -70,6 +70,15 @@ struct SkippedFieldObj {
skipped: i32,
}
struct Context;
impl juniper::Context for Context {}
#[derive(GraphQLObject, Debug)]
#[graphql(Context = "Context")]
struct WithCustomContext {
a: bool,
}
graphql_object!(Query: () |&self| {
field obj() -> Obj {
Obj{

View file

@ -8,6 +8,7 @@ use util::*;
struct ObjAttrs {
name: Option<String>,
description: Option<String>,
context: Option<Ident>,
scalar: Option<Ident>,
}
@ -46,6 +47,10 @@ impl ObjAttrs {
res.scalar = Some(Ident::new(&scalar as &str, Span::call_site()));
continue;
}
if let Some(AttributeValue::String(ctx)) = keyed_item_value(&item, "Context", AttributeValidation::String) {
res.context = Some(Ident::new(&ctx as &str, Span::call_site()));
continue;
}
panic!(format!(
"Unknown struct attribute for #[derive(GraphQLObject)]: {:?}",
item
@ -223,13 +228,15 @@ pub fn impl_object(ast: &syn::DeriveInput) -> TokenStream {
.scalar
.unwrap_or_else(|| Ident::new("__S", Span::call_site()));
let ctx = attrs.context.map(|ident| quote!( #ident )).unwrap_or(quote!( () ));
let (impl_generics, _, where_clause) = generics.split_for_impl();
let body = quote! {
impl#impl_generics juniper::GraphQLType<#scalar> for #ident #ty_generics
#where_clause
{
type Context = ();
type Context = #ctx;
type TypeInfo = ();
fn name(_: &()) -> Option<&str> {