Skip to content
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

Allow down casting query trail interface and union types #63

Merged
merged 1 commit into from
Oct 5, 2019
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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ for Rust libraries in [RFC #1105](https://github.com/rust-lang/rfcs/blob/master/

### Added

N/A
- Support converting `QueryTrail`s for interfaces or unions into `QueryTrail`s for implementors of those interfaces or unions. This makes it possible to use [juniper-eager-loading](https://crates.io/crates/juniper-eager-loading) with interface or union types. [#63](https://github.com/davidpdrsn/juniper-from-schema/pull/63)

### Changed

Expand Down
1 change: 1 addition & 0 deletions juniper-from-schema-code-gen/src/ast_pass/ast_data_pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use graphql_parser::{
};
use std::collections::{BTreeSet, HashMap, HashSet};

#[derive(Debug)]
pub struct AstData<'doc> {
interface_implementors: HashMap<&'doc str, Vec<&'doc str>>,
user_scalars: HashSet<&'doc str>,
Expand Down
1 change: 1 addition & 0 deletions juniper-from-schema-code-gen/src/ast_pass/code_gen_pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use syn::Ident;

type Result<T, E = ()> = std::result::Result<T, E>;

#[derive(Debug)]
pub struct CodeGenPass<'doc> {
tokens: TokenStream,
error_type: syn::Type,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::{
collections::{HashMap, HashSet},
hash::{Hash, Hasher},
};
use syn::Ident;

impl<'doc> CodeGenPass<'doc> {
pub fn gen_query_trails(&mut self, doc: &'doc Document) {
Expand Down Expand Up @@ -95,7 +96,49 @@ impl<'doc> CodeGenPass<'doc> {
impl<'a, K> QueryTrail<'a, #name, K> {
#(#methods)*
}
})
});

self.gen_conversion_methods(name, obj);
}

fn gen_conversion_methods(
&mut self,
original_type_name: Ident,
obj: InternalQueryTrailNode<'_>,
) {
let mut destination_types = vec![];

match obj {
InternalQueryTrailNode::Object(_) => {}
InternalQueryTrailNode::Interface(i) => {
if let Some(i) = &self.ast_data.get_implementors_of_interface(&i.name) {
for interface_implementor_name in *i {
let ident = ident(interface_implementor_name);
destination_types.push(ident);
}
}
}
InternalQueryTrailNode::Union(u, _) => {
for type_ in &u.types {
let ident = ident(type_);
destination_types.push(ident);
}
}
}

for type_ in destination_types {
self.extend(quote! {
impl<'a> Into<QueryTrail<'a, #type_, Walked>> for &QueryTrail<'a, #original_type_name, Walked> {
fn into(self) -> QueryTrail<'a, #type_, Walked> {
QueryTrail {
look_ahead: self.look_ahead,
node_type: std::marker::PhantomData,
walked: juniper_from_schema::Walked,
}
}
}
});
}
}

fn error_msg_if_field_types_dont_overlap(
Expand Down
125 changes: 125 additions & 0 deletions juniper-from-schema/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,131 @@
//! You can always run `cargo doc` and inspect all the methods on `QueryTrail` and in which
//! contexts you can call them.
//!
//! ## Downcasting for interface and union `QueryTrail`s
//!
//! _This section is mostly relevant if you're using
//! [juniper-eager-loading](https://crates.io/crates/juniper-eager-loading) however it isn't
//! specific to that library._
//!
//! If you have a `QueryTrail<'a, T, Walked>` where `T` is an interface or union type you can use
//! `.into()` to convert that `QueryTrail` into one of the implementors of the interface or union.
//!
//! Example:
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Article { id: ID }
//! # impl ArticleFields for Article {
//! # fn field_id(
//! # &self,
//! # executor: &Executor<'_, Context>,
//! # ) -> FieldResult<&ID> { unimplemented!() }
//! # }
//! # pub struct Tweet { id: ID, text: String }
//! # impl TweetFields for Tweet {
//! # fn field_id(
//! # &self,
//! # executor: &Executor<'_, Context>,
//! # ) -> FieldResult<&ID> { unimplemented!() }
//! # }
//! #
//! graphql_schema! {
//! schema {
//! query: Query
//! }
//!
//! type Query {
//! search(query: String!): [SearchResult!]!
//! }
//!
//! interface SearchResult {
//! id: ID!
//! }
//!
//! type Article implements SearchResult {
//! id: ID!
//! }
//!
//! type Tweet implements SearchResult {
//! id: ID!
//! }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//! fn field_search(
//! &self,
//! executor: &Executor<'_, Context>,
//! trail: &QueryTrail<'_, SearchResult, juniper_from_schema::Walked>,
//! query: String,
//! ) -> FieldResult<&Vec<SearchResult>> {
//! let article_trail: QueryTrail<'_, Article, Walked> = trail.into();
//! let tweet_trail: QueryTrail<'_, Tweet, Walked> = trail.into();
//!
//! // ...
//! # unimplemented!()
//! }
//! }
//! ```
//!
//! ### Why is this useful?
//!
//! If you were do perform some kind of preloading of data you might have a function that inspects
//! a `QueryTrail` and load the necessary data from a database. Such a function could look like
//! this:
//!
//! ```ignore
//! fn preload_users(
//! mut users: Vec<User>,
//! query_trail: &QueryTrail<'_, User, Walked>,
//! db: &Database,
//! ) -> Vec<User> {
//! // ...
//! }
//! ```
//!
//! This function works well when we have field that returns `[User!]!`. That field is going to get
//! a `QueryTrail<'a, User, Walked>` which is exactly what `preload_users` needs.
//!
//! However, now imagine you have a schema like this:
//!
//! ```graphql
//! type Query {
//! search(query: String!): [SearchResult!]!
//! }
//!
//! union SearchResult = User | City | Country
//!
//! type User {
//! id: ID!
//! city: City!
//! }
//!
//! type City {
//! id: ID!
//! country: Country!
//! }
//!
//! type Country {
//! id: ID!
//! }
//! ```
//!
//! The method `QueryFields::field_seach` will receive a `QueryTrail<'a, SearchResult, Walked>`.
//! That type doesn't work with `preload_users`. So we have to convert our `QueryTrail<'a,
//! SearchResult, Walked>` into `QueryTrail<'a, User, Walked>`.
//!
//! This can be done [`std::convert::Into`](https://doc.rust-lang.org/std/convert/trait.Into.html)
//! which automatically gets implemented for interface and union query trails. See above for an
//! example.
//!
//! # Customizing the error type
//!
//! By default the return type of the generated field methods will be [`juniper::FieldResult<T>`].
Expand Down
159 changes: 159 additions & 0 deletions juniper-from-schema/tests/converting_query_trails_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#![allow(dead_code, unused_variables, unused_must_use, unused_imports)]
use juniper::{EmptyMutation, Executor, FieldResult, Variables};
use juniper_from_schema::{graphql_schema, graphql_schema_from_file};

pub struct Context;
impl juniper::Context for Context {}

graphql_schema! {
type Query {
entities: [Entity!]! @juniper(ownership: "owned")
search(query: String!): [SearchResult!]! @juniper(ownership: "owned")
}

interface Entity {
id: Int! @juniper(ownership: "owned")
name: String!
}

type User implements Entity {
id: Int! @juniper(ownership: "owned")
name: String!
}

union SearchResult = User

schema {
query: Query
}
}

pub struct Query;

impl QueryFields for Query {
fn field_entities<'a>(
&self,
executor: &Executor<'a, Context>,
trail: &QueryTrail<'a, Entity, Walked>,
) -> FieldResult<Vec<Entity>> {
verify_entity_query_trail(trail);
verify_user_query_trail(&trail.into());

Ok(vec![])
}

fn field_search<'a>(
&self,
executor: &Executor<'a, Context>,
trail: &QueryTrail<'a, SearchResult, Walked>,
_query: String,
) -> FieldResult<Vec<SearchResult>> {
verify_search_result_query_trail(trail);
verify_user_query_trail(&trail.into());

Ok(vec![])
}
}

fn verify_entity_query_trail<'a>(trail: &QueryTrail<'a, Entity, Walked>) {
if !trail.id() {
panic!("Entity.id missing from trail")
}
}

fn verify_search_result_query_trail<'a>(trail: &QueryTrail<'a, SearchResult, Walked>) {
if !trail.id() {
panic!("id missing from trail")
}
}

fn verify_user_query_trail<'a>(trail: &QueryTrail<'a, User, Walked>) {
if !trail.id() {
panic!("User.id missing from trail")
}
}

pub struct User {
id: i32,
name: String,
}

impl UserFields for User {
fn field_id<'a>(&self, executor: &Executor<'a, Context>) -> FieldResult<i32> {
Ok(self.id)
}

fn field_name<'a>(&self, executor: &Executor<'a, Context>) -> FieldResult<&String> {
Ok(&self.name)
}
}

#[test]
fn test_converting_interface_trails() {
query(
r#"
query {
entities {
id
}
}
"#,
);
}

#[test]
#[should_panic]
fn test_converting_interface_trails_negative() {
query(
r#"
query {
entities {
name
}
}
"#,
);
}

#[test]
fn test_converting_union_trails() {
query(
r#"
query {
search(query: "foo") {
... on User {
id
}
}
}
"#,
);
}

#[test]
#[should_panic]
fn test_converting_union_trails_negative() {
query(
r#"
query {
search(query: "foo") {
... on User {
name
}
}
}
"#,
);
}

fn query(query: &str) {
let ctx = Context;
let (juniper_value, _errors) = juniper::execute(
query,
None,
&Schema::new(Query, juniper::EmptyMutation::new()),
&Variables::new(),
&ctx,
)
.unwrap();
}