Important notice: This project is still in a very experimental state. It does work but the API might change drastically.
This library exposes a procedural macro that reads a GraphQL schema file, and generates the corresponding Juniper macro calls. This means you can have a real schema file and be guaranteed that it matches your Rust implementation. It also removes most of the boilerplate from using Juniper.
Schema:
```graphql schema { query: Query mutation: Mutation }
type Query {
// this makes the return value FieldResult<String>
// rather than the default FieldResult<&String>
"#[ownership(owned)]"
helloWorld(name: String!): String!
}
type Mutation { noop: Boolean! } ```
Rust implementation of schema:
```rust
extern crate juniper;
use juniper::*; use juniperfromschema::graphqlschemafrom_file;
// This is the important line graphqlschemafromfile!("tests/schemas/docschema.graphql");
pub struct Context; impl juniper::Context for Context {}
pub struct Query;
impl QueryFields for Query {
fn fieldhelloworld(
&self,
executor: &Executor<'_, Context>,
name: String,
) -> FieldResult
pub struct Mutation;
impl MutationFields for Mutation { fn fieldnoop(&self, executor: &Executor<', Context>) -> FieldResult<&bool> { Ok(&true) } }
fn main() { let ctx = Context;
let query = "query { helloWorld(name: \"Ferris\") }";
let (result, errors) = juniper::execute(
query,
None,
&Schema::new(Query, Mutation),
&Variables::new(),
&ctx,
)
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(
result
.as_object_value()
.unwrap()
.get_field_value("helloWorld")
.unwrap()
.as_scalar_value::<String>()
.unwrap(),
"Hello, Ferris!",
);
} ```
This expands into:
```rust
extern crate juniper;
use juniper::*;
pub struct Context; impl juniper::Context for Context {}
pub struct Query;
graphqlobject!(Query: Context |&self| {
field helloworld(&executor, name: String) -> FieldResult
trait QueryFields {
fn fieldhelloworld(
&self,
executor: &Executor<'_, Context>,
name: String,
) -> FieldResult
impl QueryFields for Query {
fn fieldhelloworld(
&self,
executor: &Executor<'_, Context>,
name: String,
) -> FieldResult
pub struct Mutation;
graphqlobject!(Mutation: Context |&self| {
field noop(&executor) -> FieldResult<&bool> {
trait MutationFields { fn fieldnoop(&self, executor: &Executor<', Context>) -> FieldResult<&bool>; }
impl MutationFields for Mutation { fn fieldnoop(&self, executor: &Executor<', Context>) -> FieldResult<&bool> { Ok(&true) } }
type Schema = juniper::RootNode<'static, Query, Mutation>;
fn main() { let ctx = Context;
let query = "query { helloWorld(name: \"Ferris\") }";
let (result, errors) = juniper::execute(
query,
None,
&Schema::new(Query, Mutation),
&Variables::new(),
&ctx,
)
.unwrap();
assert_eq!(errors.len(), 0);
assert_eq!(
result
.as_object_value()
.unwrap()
.get_field_value("helloWorld")
.unwrap()
.as_scalar_value::<String>()
.unwrap(),
"Hello, Ferris!",
);
} ```
By default all fields return borrowed values. Specifically the type is
juniper::FieldResult<&'a T>
where 'a
is the lifetime of self
. This works well for
returning data owned by self
and avoids needless .clone()
calls you would need if fields
returned owned values.
However if you need to return owned values (such as values queried from a database) you have to
annotate the field in the schema with #[ownership(owned)]
.
All field arguments will be owned.
The goal of this library is to support as much of GraphQL as Juniper does.
Here is the complete list of features:
Supported:
- Object types including converting lists on non-nulls to Rust types
- Custom scalar types including the ID
type
- Interfaces
- Unions
- Input objects
- Enumeration types
Not supported yet: - Default values for arguments - Subscriptions (currently not supported by Juniper so we're unsure when or if this will happen)
ID
typeThe ID
GraphQL type will be generated as a newtype wrapper around a String
using
juniper::graphql_scalar!
. The Rust type will be called Id
.
Example:
```rust pub struct Id(pub String);
impl Id {
// A generated convenience initializer
pub fn new
Similarly to ID
, custom scalar types get converted into newtype wrappers around String
s. For example:
graphql
scalar Cursor
Would result in
rust
pub struct Cursor(pub String);
Date
and DateTime
are the two exceptions to this. Date
gets converted into
chrono::naive::NaiveDate
and DateTime
into
chrono::DateTime<chrono::offset::Utc>
.
Juniper has several ways of representing GraphQL interfaces in Rust. They are listed here along with their advantages and disadvantages.
For the generated code we use the enum
pattern because we found it to be the most flexible.
Example:
```rust # graphql_schema! { schema { query: Query }
type Query {
"#[ownership(owned)]"
search(query: String!): [SearchResult!]!
}
interface SearchResult {
id: ID!
text: String!
}
type Article implements SearchResult {
id: ID!
text: String!
}
type Tweet implements SearchResult {
id: ID!
text: String!
}
}
pub struct Query;
impl QueryFields for Query {
fn fieldsearch(
&self,
executor: &Executor<', Context>,
trail: &QueryTrail<', SearchResult, Walked>,
query: String,
) -> FieldResult
let posts = vec![
SearchResult::from(article),
SearchResult::from(tweet),
];
Ok(posts)
}
} ```
The enum that gets generated has variants for each type that implements the interface and also
implements From<T>
for each type.
Union types are basically just interfaces so they work in very much the same way.
Example:
```rust # graphql_schema! { schema { query: Query }
type Query {
"#[ownership(owned)]"
search(query: String!): [SearchResult!]!
}
union SearchResult = Article | Tweet
type Article {
id: ID!
text: String!
}
type Tweet {
id: ID!
text: String!
}
}
pub struct Query;
impl QueryFields for Query {
fn fieldsearch(
&self,
executor: &Executor<', Context>,
trail: &QueryTrail<', SearchResult, Walked>,
query: String,
) -> FieldResult
let posts = vec![
SearchResult::from(article),
SearchResult::from(tweet),
];
Ok(posts)
}
} ```
Input objects will be converted into Rust structs with public fields.
Example:
```rust graphql_schema! { schema { query: Query mutation: Mutation }
type Mutation {
"#[ownership(owned)]"
createPost(input: CreatePost!): Post
}
input CreatePost {
title: String!
}
type Post {
id: ID!
title: String!
}
type Query { noop: Boolean! }
}
pub struct Mutation;
impl MutationFields for Mutation { fn fieldcreatepost( &self, executor: &Executor<', Context>, trail: &QueryTrail<', Post, Walked>, input: CreatePost, ) -> FieldResult
unimplemented!()
}
} ```
From that example CreatePost
will be defined as
rust
pub struct CreatePost {
pub title: String,
}
GraphQL enumeration types will be converted into normal Rust enums. The name of each variant will be camel cased.
Example:
```rust # graphql_schema! { schema { query: Query }
enum Status {
PUBLISHED
UNPUBLISHED
}
type Query {
"#[ownership(owned)]"
allPosts(status: STATUS!): [Post!]!
}
type Post {
id: ID!
}
}
pub struct Query;
impl QueryFields for Query {
fn fieldallposts(
&self,
executor: &Executor<', Context>,
trail: &QueryTrail<', Post, Walked>,
status: Status,
) -> FieldResult
This is how the standard GraphQL types will be mapped to Rust:
Int
-> i32
Float
-> f64
String
-> String
Boolean
-> bool
ID
-> pub struct Id(pub String)
If you're not careful about preloading associations for deeply nested queries you risk getting lots of N+1 query bugs. Juniper provides a look ahead api which lets you inspect things coming up further down a query. However the API is string based, so you risk making typos and checking for fields that don't exist.
QueryTrail
is a thin wrapper around Juniper look aheads with generated methods for each field
on all your types. This means the compiler will reject your code if you're checking for invalid
fields.
Fields that return objects types (non scalar values) will also get a QueryTrail
argument
besides the executor.
```rust # graphql_schema! { schema { query: Query }
type Query {
"#[ownership(owned)]"
allPosts: [Post!]!
}
type Post {
id: Int!
author: User!
}
type User {
id: Int!
}
}
pub struct Query;
impl QueryFields for Query {
fn fieldallposts(
&self,
executor: &Executor<', Context>,
trail: &QueryTrail<', Post, Walked>,
) -> FieldResult
// Normally this would come from the database
let post = Post {
id: 1,
author: User { id: 1 },
};
Ok(vec![post])
}
}
pub struct Post { id: i32, author: User, }
impl PostFields for Post { fn fieldid(&self, executor: &Executor<', Context>) -> FieldResult<&i32> { Ok(&self.id) }
fn field_author(
&self,
executor: &Executor<'_, Context>,
trail: &QueryTrail<'_, User, Walked>,
) -> FieldResult<&User> {
Ok(&self.author)
}
}
pub struct User { id: i32, }
impl UserFields for User { fn fieldid( &self, executor: &Executor<', Context>, ) -> FieldResult<&i32> { Ok(&self.id) } } ```
A query trial has two generic parameters: QueryTrail<'_, T, K>
. T
is the type the current
field returns and K
is either Walked
or NotWalked
.
T
The T
allows us to implement different methods for different types. For example in the
example above we implement id
and author
for QueryTrail<'_, Post, K>
but only id
for
QueryTrail<'_, User, K>
.
K
The Walked
and NotWalked
types are used to check if a given trail has been checked to
actually be part of a query. Calling any method on a QueryTrail<'_, T, K>
will return
QueryTrail<'_, T, NotWalked>
, and to check if the trail is actually part of the query you have
to call .walk()
which returns Option<QueryTrail<'_, T, Walked>>
. If that is a Some(_)
you'll know the trail is part of the query and you can do whatever preloading is necessary.
Example:
rust
if let Some(walked_trail) = trail.some_field().some_other_field().third_field().walk() {
// preload stuff
}
You can always run cargo doc
and inspect all the methods on QueryTrail
and in which
contexts you can call them.
License: MIT