11use failure;
2- use field_type:: FieldType ;
32use fragments:: GqlFragment ;
4- use proc_macro2:: TokenStream ;
3+ use graphql_parser;
4+ use proc_macro2:: { Ident , Span , TokenStream } ;
55use schema:: Schema ;
66use selection:: Selection ;
77use std:: collections:: BTreeMap ;
8+ use variables:: Variable ;
89
910pub struct QueryContext {
1011 pub _subscription_root : Option < Vec < TokenStream > > ,
1112 pub fragments : BTreeMap < String , GqlFragment > ,
1213 pub mutation_root : Option < Vec < TokenStream > > ,
1314 pub query_root : Option < Vec < TokenStream > > ,
1415 pub schema : Schema ,
15- pub variables : BTreeMap < String , FieldType > ,
16+ pub variables : Vec < Variable > ,
1617}
1718
1819impl QueryContext {
@@ -23,7 +24,34 @@ impl QueryContext {
2324 mutation_root : None ,
2425 query_root : None ,
2526 schema,
26- variables : BTreeMap :: new ( ) ,
27+ variables : Vec :: new ( ) ,
28+ }
29+ }
30+
31+ pub fn register_variables ( & mut self , variables : & [ graphql_parser:: query:: VariableDefinition ] ) {
32+ variables. iter ( ) . for_each ( |variable| {
33+ self . variables . push ( variable. clone ( ) . into ( ) ) ;
34+ } ) ;
35+ }
36+
37+ pub fn expand_variables ( & self ) -> TokenStream {
38+ if self . variables . is_empty ( ) {
39+ return quote ! ( #[ derive( Serialize ) ]
40+ pub struct Variables ; ) ;
41+ }
42+
43+ let fields = self . variables . iter ( ) . map ( |variable| {
44+ let name = & variable. name ;
45+ let ty = variable. ty . to_rust ( self , name) ;
46+ let name = Ident :: new ( name, Span :: call_site ( ) ) ;
47+ quote ! ( pub #name: #ty)
48+ } ) ;
49+
50+ quote ! {
51+ #[ derive( Serialize ) ]
52+ pub struct Variables {
53+ #( #fields, ) *
54+ }
2755 }
2856 }
2957
@@ -36,7 +64,7 @@ impl QueryContext {
3664 mutation_root : None ,
3765 query_root : None ,
3866 schema : Schema :: new ( ) ,
39- variables : BTreeMap :: new ( ) ,
67+ variables : Vec :: new ( ) ,
4068 }
4169 }
4270
0 commit comments