11use field_type:: FieldType ;
22use graphql_parser;
3+ use proc_macro2:: { Ident , Span , TokenStream } ;
4+ use query:: QueryContext ;
35
46#[ derive( Debug ) ]
57pub struct Variable {
@@ -8,6 +10,25 @@ pub struct Variable {
810 pub default : Option < graphql_parser:: query:: Value > ,
911}
1012
13+ impl Variable {
14+ pub fn generate_default_value_constructor ( & self , context : & QueryContext ) -> TokenStream {
15+ match & self . default {
16+ Some ( default) => {
17+ let fn_name = Ident :: new ( & format ! ( "default_{}" , self . name) , Span :: call_site ( ) ) ;
18+ let ty = self . ty . to_rust ( context, "" ) ;
19+ let value = graphql_parser_value_to_literal ( default, self . ty . is_optional ( ) ) ;
20+ quote ! {
21+ pub fn #fn_name( ) -> #ty {
22+ #value
23+ }
24+
25+ }
26+ }
27+ None => quote ! ( ) ,
28+ }
29+ }
30+ }
31+
1132impl :: std:: convert:: From < graphql_parser:: query:: VariableDefinition > for Variable {
1233 fn from ( def : graphql_parser:: query:: VariableDefinition ) -> Variable {
1334 Variable {
@@ -17,3 +38,44 @@ impl ::std::convert::From<graphql_parser::query::VariableDefinition> for Variabl
1738 }
1839 }
1940}
41+
42+ fn graphql_parser_value_to_literal (
43+ value : & graphql_parser:: query:: Value ,
44+ is_optional : bool ,
45+ ) -> TokenStream {
46+ use graphql_parser:: query:: Value ;
47+
48+ let inner = match value {
49+ Value :: Boolean ( b) => if * b {
50+ quote ! ( true )
51+ } else {
52+ quote ! ( false )
53+ } ,
54+ Value :: String ( s) => quote ! ( #s. to_string( ) ) ,
55+ Value :: Variable ( _) => panic ! ( "variable in variable" ) ,
56+ Value :: Null => panic ! ( "null as default value" ) ,
57+ Value :: Float ( f) => quote ! ( #f) ,
58+ Value :: Int ( i) => {
59+ let i = i. as_i64 ( ) ;
60+ quote ! ( #i)
61+ }
62+ Value :: Enum ( en) => quote ! ( #en) ,
63+ Value :: List ( inner) => {
64+ let elements = inner
65+ . iter ( )
66+ . map ( |val| graphql_parser_value_to_literal ( val, false ) ) ;
67+ quote ! {
68+ vec![
69+ #( #elements, ) *
70+ ]
71+ }
72+ }
73+ Value :: Object ( _) => unimplemented ! ( "object literal as default for variable" ) ,
74+ } ;
75+
76+ if is_optional {
77+ quote ! ( Some ( #inner) )
78+ } else {
79+ inner
80+ }
81+ }
0 commit comments