Skip to content

Commit 464fb31

Browse files
committed
Generate something more plausible for unions
This will have to be tested.
1 parent dd4cd4a commit 464fb31

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

graphql_query_derive/src/unions.rs

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,21 @@ impl GqlUnion {
2424
) -> Result<TokenStream, failure::Error> {
2525
let struct_name = Ident::new(prefix, Span::call_site());
2626
let mut children_definitions: Vec<TokenStream> = Vec::new();
27-
let fields: Result<Vec<TokenStream>, failure::Error> = selection.0.iter().map(|item| {
27+
let variants: Result<Vec<TokenStream>, failure::Error> = selection.0.iter().map(|item| {
2828
match item {
2929
SelectionItem::Field(_) => unreachable!("field selection on union"),
3030
SelectionItem::FragmentSpread(_) => unreachable!("fragment spread on union"),
3131
SelectionItem::InlineFragment(frag) => {
32-
let field_name = Ident::new(
33-
&format!("on_{}", frag.on).to_snake_case(),
32+
let variant_name = Ident::new(
33+
&frag.on,
3434
Span::call_site(),
3535
);
3636

37-
let field_type = Ident::new(&format!("{}On{}", prefix, frag.on), Span::call_site());
38-
3937
let new_prefix = format!("{}On{}", prefix, frag.on);
4038

39+
let variant_type = Ident::new(&new_prefix, Span::call_site());
40+
41+
4142
let field_object_type = query_context.schema.objects.get(&frag.on)
4243
.map(|f| query_context.maybe_expand_field(&frag.on, &frag.fields, &new_prefix));
4344
let field_interface = query_context.schema.interfaces.get(&frag.on)
@@ -52,20 +53,21 @@ impl GqlUnion {
5253
};
5354

5455
Ok(quote! {
55-
#field_name: #field_type
56+
#variant_name(#variant_type)
5657
})
5758
}
5859
}
5960
}).collect();
6061

61-
let fields = fields?;
62+
let variants = variants?;
6263

6364
Ok(quote!{
6465
#(#children_definitions)*
6566

6667
#[derive(Deserialize)]
67-
pub struct #struct_name {
68-
#(#fields),*
68+
#[serde(tag = "__typename")]
69+
pub enum #struct_name {
70+
#(#variants),*
6971
}
7072
})
7173
}
@@ -161,7 +163,9 @@ mod tests {
161163
"pub struct MeowOnUser { first_name : String , } ",
162164
"# [ derive ( Debug , Serialize , Deserialize ) ] ",
163165
"pub struct MeowOnOrganization { title : String , } ",
164-
"# [ derive ( Deserialize ) ] pub struct Meow { on_user : MeowOnUser , on_organization : MeowOnOrganization }",
166+
"# [ derive ( Deserialize ) ] ",
167+
"# [ serde ( tag = \"__typename\" ) ] ",
168+
"pub enum Meow { User ( MeowOnUser ) , Organization ( MeowOnOrganization ) }",
165169
].into_iter().collect::<String>(),
166170
);
167171
}

0 commit comments

Comments
 (0)