Skip to content

Support selecting an operation inside a query document #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions examples/github/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ fn main() -> Result<(), failure::Error> {
.header(reqwest::header::Authorization(format!(
"bearer {}",
config.github_api_token
)))
.json(&q)
))).json(&q)
.send()?;

let response_body: GraphQLResponse<query1::ResponseData> = res.json()?;
Expand Down
150 changes: 123 additions & 27 deletions graphql_query_derive/src/codegen.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,129 @@
use field_type::FieldType;
use std::collections::BTreeMap;

#[derive(Debug)]
pub struct StructFieldDescriptor {
pub attributes: TokenStream,
pub name: String,
pub ty: FieldType,
}
use failure;
use fragments::GqlFragment;
use graphql_parser::query;
use operations::Operation;
use proc_macro2::TokenStream;
use query::QueryContext;
use schema;
use selection::Selection;

#[derive(Debug)]
pub struct StructDescriptor {
pub attributes: TokenStream,
pub fields: Vec<StructFieldDescriptor>,
pub name: String,
}
pub(crate) fn response_for_query(
schema: schema::Schema,
query: query::Document,
selected_operation: String,
) -> Result<TokenStream, failure::Error> {
let mut context = QueryContext::new(schema);
let mut definitions = Vec::new();
let mut operations: Vec<Operation> = Vec::new();

impl StructDescriptor {
pub fn field_by_name(&self, name: &str) -> Option<StructFieldDescriptor> {
unimplemented!()
for definition in query.definitions {
match definition {
query::Definition::Operation(op) => {
operations.push(op.into());
}
query::Definition::Fragment(fragment) => {
let query::TypeCondition::On(on) = fragment.type_condition;
context.fragments.insert(
fragment.name.clone(),
GqlFragment {
name: fragment.name,
selection: Selection::from(&fragment.selection_set),
on,
},
);
}
}
}
}

pub struct EnumVariantDescriptor {
pub attributes: TokenStream,
pub name: String,
}
context.selected_operation = operations
.iter()
.find(|op| op.name == selected_operation)
.map(|i| i.to_owned());

let operation = context.selected_operation.clone().unwrap_or_else(|| {
operations
.iter()
.next()
.map(|i| i.to_owned())
.expect("no operation in query document")
});

let response_data_fields = {
let root_name: String = operation
.root_name(&context.schema)
.expect("operation type not in schema");
let definition = context
.schema
.objects
.get(&root_name)
.expect("schema declaration is invalid");
let prefix = format!("RUST_{}", operation.name);
let selection = &operation.selection;

if operation.is_subscription() && selection.0.len() > 1 {
Err(format_err!(
"{}",
::constants::MULTIPLE_SUBSCRIPTION_FIELDS_ERROR
))?
}

definitions.extend(
definition
.field_impls_for_selection(&context, &selection, &prefix)
.unwrap(),
);
definition
.response_fields_for_selection(&context, &selection, &prefix)
.unwrap()
};

let enum_definitions = context.schema.enums.values().map(|enm| enm.to_rust());
let fragment_definitions: Result<Vec<TokenStream>, _> = context
.fragments
.values()
.map(|fragment| fragment.to_rust(&context))
.collect();
let fragment_definitions = fragment_definitions?;
let variables_struct = operation.expand_variables(&context);

let input_object_definitions: Result<Vec<TokenStream>, _> = context
.schema
.inputs
.values()
.map(|i| i.to_rust(&context))
.collect();
let input_object_definitions = input_object_definitions?;

let scalar_definitions: Vec<TokenStream> = context
.schema
.scalars
.values()
.map(|s| s.to_rust())
.collect();

Ok(quote! {
type Boolean = bool;
type Float = f64;
type Int = i64;
type ID = String;

#(#scalar_definitions)*

#(#input_object_definitions)*

#(#enum_definitions)*

#(#fragment_definitions)*

#(#definitions)*

#variables_struct

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseData {
#(#response_data_fields,)*
}

#[derive(Debug)]
pub struct EnumDescriptor {
pub name: String,
pub variants: Vec<String>,
})
}
39 changes: 34 additions & 5 deletions graphql_query_derive/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ use field_type::FieldType;
use objects::GqlObjectField;
use proc_macro2::{Ident, Span};

pub const TYPENAME_FIELD: &str = "__typename";
pub(crate) const TYPENAME_FIELD: &str = "__typename";

pub fn string_type() -> Ident {
pub(crate) fn string_type() -> Ident {
Ident::new("String", Span::call_site())
}

#[cfg(test)]
pub fn float_type() -> Ident {
pub(crate) fn float_type() -> Ident {
Ident::new("Float", Span::call_site())
}

pub fn typename_field() -> GqlObjectField {
pub(crate) fn typename_field() -> GqlObjectField {
GqlObjectField {
description: None,
name: TYPENAME_FIELD.to_string(),
Expand All @@ -23,8 +23,37 @@ pub fn typename_field() -> GqlObjectField {
}
}

pub const MULTIPLE_SUBSCRIPTION_FIELDS_ERROR: &str = r##"
pub(crate) const MULTIPLE_SUBSCRIPTION_FIELDS_ERROR: &str = r##"
Multiple-field queries on the root subscription field are forbidden by the spec.

See: https://github.com/facebook/graphql/blob/master/spec/Section%205%20--%20Validation.md#subscription-operation-definitions
"##;

/// Error message when a selection set is the root of a query.
pub(crate) const SELECTION_SET_AT_ROOT: &str = r#"
Operations in queries must be named.

Instead of this:

{
user {
name
repositories {
name
commits
}
}
}

Write this:

query UserRepositories {
user {
name
repositories {
name
commits
}
}
}
"#;
6 changes: 2 additions & 4 deletions graphql_query_derive/src/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ impl GqlEnum {
let description = &v.description;
let description = description.as_ref().map(|d| quote!(#[doc = #d]));
quote!(#description #name)
})
.collect();
}).collect();
let variant_names = &variant_names;
let name_ident = Ident::new(&format!("{}{}", ENUMS_PREFIX, self.name), Span::call_site());
let constructors: Vec<_> = self
Expand All @@ -35,8 +34,7 @@ impl GqlEnum {
.map(|v| {
let v = Ident::new(&v.name, Span::call_site());
quote!(#name_ident::#v)
})
.collect();
}).collect();
let constructors = &constructors;
let variant_str: Vec<&str> = self.variants.iter().map(|v| v.name.as_str()).collect();
let variant_str = &variant_str;
Expand Down
9 changes: 4 additions & 5 deletions graphql_query_derive/src/field_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub enum FieldType {

impl FieldType {
/// Takes a field type with its name
pub fn to_rust(&self, context: &QueryContext, prefix: &str) -> TokenStream {
pub(crate) fn to_rust(&self, context: &QueryContext, prefix: &str) -> TokenStream {
let prefix: String = if prefix.is_empty() {
self.inner_name_string()
} else {
Expand All @@ -24,10 +24,9 @@ impl FieldType {
FieldType::Named(name) => {
let name_string = name.to_string();

let name = if context.schema.scalars.contains_key(&name_string)
|| DEFAULT_SCALARS
.iter()
.any(|elem| elem == &name_string.as_str())
let name = if context.schema.scalars.contains_key(&name_string) || DEFAULT_SCALARS
.iter()
.any(|elem| elem == &name_string.as_str())
{
name.clone()
} else if context.schema.enums.contains_key(&name_string) {
Expand Down
2 changes: 1 addition & 1 deletion graphql_query_derive/src/fragments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct GqlFragment {
}

impl GqlFragment {
pub fn to_rust(&self, context: &QueryContext) -> Result<TokenStream, ::failure::Error> {
pub(crate) fn to_rust(&self, context: &QueryContext) -> Result<TokenStream, ::failure::Error> {
let name_ident = Ident::new(&self.name, Span::call_site());
let object = context.schema.objects.get(&self.on).expect("oh, noes");
let field_impls = object.field_impls_for_selection(context, &self.selection, &self.name)?;
Expand Down
12 changes: 5 additions & 7 deletions graphql_query_derive/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub struct GqlInput {
}

impl GqlInput {
pub fn to_rust(&self, context: &QueryContext) -> Result<TokenStream, failure::Error> {
pub(crate) fn to_rust(&self, context: &QueryContext) -> Result<TokenStream, failure::Error> {
let name = Ident::new(&self.name, Span::call_site());
let mut fields: Vec<&GqlObjectField> = self.fields.values().collect();
fields.sort_unstable_by(|a, b| a.name.cmp(&b.name));
Expand Down Expand Up @@ -52,8 +52,7 @@ impl ::std::convert::From<graphql_parser::schema::InputObjectType> for GqlInput
type_: field.value_type.into(),
};
(name, field)
})
.collect(),
}).collect(),
}
}
}
Expand All @@ -80,8 +79,7 @@ impl ::std::convert::From<introspection_response::FullType> for GqlInput {
.into(),
};
(name, field)
})
.collect(),
}).collect(),
}
}
}
Expand Down Expand Up @@ -129,7 +127,7 @@ mod tests {
},
),
].into_iter()
.collect(),
.collect(),
};

let expected: String = vec![
Expand All @@ -141,7 +139,7 @@ mod tests {
"pub requirements : Option < CatRequirements > , ",
"}",
].into_iter()
.collect();
.collect();

let mut context = QueryContext::new_empty();
context.schema.inputs.insert(cat.name.clone(), cat);
Expand Down
2 changes: 1 addition & 1 deletion graphql_query_derive/src/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl GqlInterface {
}
}

pub fn response_for_selection(
pub(crate) fn response_for_selection(
&self,
query_context: &QueryContext,
selection: &Selection,
Expand Down
7 changes: 4 additions & 3 deletions graphql_query_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ extern crate quote;

use proc_macro2::TokenStream;

mod codegen;
mod constants;
mod enums;
mod field_type;
Expand All @@ -24,6 +25,7 @@ mod inputs;
mod interfaces;
mod introspection_response;
mod objects;
mod operations;
mod query;
mod scalars;
mod schema;
Expand Down Expand Up @@ -106,7 +108,7 @@ fn impl_gql_query(input: &syn::DeriveInput) -> Result<TokenStream, failure::Erro

let module_name = Ident::new(&input.ident.to_string().to_snake_case(), Span::call_site());
let struct_name = &input.ident;
let schema_output = schema.response_for_query(query)?;
let schema_output = codegen::response_for_query(schema, query, input.ident.to_string())?;

let result = quote!(
pub mod #module_name {
Expand Down Expand Up @@ -145,8 +147,7 @@ fn extract_attr(ast: &syn::DeriveInput, attr: &str) -> Result<String, failure::E
.find(|attr| {
let path = &attr.path;
quote!(#path).to_string() == "graphql"
})
.ok_or_else(|| format_err!("The graphql attribute is missing"))?;
}).ok_or_else(|| format_err!("The graphql attribute is missing"))?;
if let syn::Meta::List(items) = &attribute
.interpret_meta()
.expect("Attribute is well formatted")
Expand Down
6 changes: 3 additions & 3 deletions graphql_query_derive/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl GqlObject {
item
}

pub fn response_for_selection(
pub(crate) fn response_for_selection(
&self,
query_context: &QueryContext,
selection: &Selection,
Expand All @@ -83,7 +83,7 @@ impl GqlObject {
})
}

pub fn field_impls_for_selection(
pub(crate) fn field_impls_for_selection(
&self,
query_context: &QueryContext,
selection: &Selection,
Expand All @@ -92,7 +92,7 @@ impl GqlObject {
field_impls_for_selection(&self.fields, query_context, selection, prefix)
}

pub fn response_fields_for_selection(
pub(crate) fn response_fields_for_selection(
&self,
query_context: &QueryContext,
selection: &Selection,
Expand Down
Loading