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

Make parsing publicly accessible #776

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ members = [
"examples/warp_async",
"examples/warp_subscriptions",
"examples/actix_subscriptions",
"examples/simple",
"integration_tests/juniper_tests",
"integration_tests/async_await",
"integration_tests/codegen_fail",
Expand Down
10 changes: 10 additions & 0 deletions examples/simple/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "simple"
version = "0.1.0"
authors = ["Miroslav Zoricak <[email protected]>"]
edition = "2018"
publish = false

[dependencies]
juniper = { git = "https://github.com/graphql-rust/juniper" }
juniper_warp = { git = "https://github.com/graphql-rust/juniper" }
59 changes: 59 additions & 0 deletions examples/simple/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use juniper::http::{GraphQLRequest, GraphQLResponse};
use juniper::Document;
use juniper::{
graphql_object, DefaultScalarValue, EmptyMutation, EmptySubscription, ParseError, RootNode,
Spanning,
};

#[derive(Clone, Copy, Debug)]
struct Context;
impl juniper::Context for Context {}

#[derive(Clone, Debug)]
struct User {
name: String,
}

#[graphql_object(Context = Context)]
impl User {
fn name(&self) -> &str {
&self.name
}
}

#[derive(Clone, Copy, Debug)]
struct Query;

#[graphql_object(Context = Context)]
impl Query {
fn users() -> Vec<User> {
vec![User {
name: "user1".into(),
}]
}
}

type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>;

fn main() {
let schema = Schema::new(
Query,
EmptyMutation::<Context>::new(),
EmptySubscription::<Context>::new(),
);
let ctx = Context {};
let query = r#" query { users { name } } "#;
let req = GraphQLRequest::<DefaultScalarValue>::new(query.to_owned(), None, None);

{
// Just parse the request query
let doc: Result<Document<DefaultScalarValue>, Spanning<ParseError>> = req.parse(&schema);
println!("{:#?}", &doc);
}

{
// Execute the query synchronously
let res: GraphQLResponse = req.execute_sync(&schema, &ctx);
println!("{:#?}", &res);
}
}
2 changes: 2 additions & 0 deletions juniper/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Features

- Added a public method for parsing queries ([#776](https://github.com/graphql-rust/juniper/pull/776))

- Added async support. ([#2](https://github.com/graphql-rust/juniper/issues/2))
- `execute()` is now async. Synchronous execution can still be used via `execute_sync()`.
- Field resolvers may optionally be declared as `async` and return a future.
Expand Down
4 changes: 4 additions & 0 deletions juniper/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ pub enum Definition<'a, S> {
Fragment(Spanning<Fragment<'a, S>>),
}

/// Parsed GraphQL request.
///
/// `S` is an instance of [ScalarValue]
/// By default [DefaultScalarValue]
pub type Document<'a, S> = Vec<Definition<'a, S>>;

/// Parse an unstructured input value into a Rust data type.
Expand Down
23 changes: 20 additions & 3 deletions juniper/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ use serde::{
};

use crate::{
ast::InputValue,
ast::{Document, InputValue},
executor::{ExecutionError, ValuesStream},
value::{DefaultScalarValue, ScalarValue},
FieldError, GraphQLError, GraphQLSubscriptionType, GraphQLType, GraphQLTypeAsync, RootNode,
Value, Variables,
FieldError, GraphQLError, GraphQLSubscriptionType, GraphQLType, GraphQLTypeAsync, ParseError,
RootNode, Spanning, Value, Variables,
};

/// The expected structure of the decoded JSON document for either POST or GET requests.
Expand Down Expand Up @@ -71,6 +71,23 @@ where
}
}

/// Parse this GraphQL request using the specified schema
///
/// This is a wrapper for the `parse_document_source` function exposed at the
/// top level of this crate.
pub fn parse<'a, QueryT, MutationT, SubscriptionT>(
&'a self,
schema: &'a RootNode<QueryT, MutationT, SubscriptionT, S>,
) -> Result<Document<'a, S>, Spanning<ParseError<'a>>>
where
S: ScalarValue,
QueryT: GraphQLType<S>,
MutationT: GraphQLType<S, Context = QueryT::Context>,
SubscriptionT: GraphQLType<S, Context = QueryT::Context>,
{
crate::parse_document_source(&self.query, &schema.schema)
}

/// Execute a GraphQL request synchronously using the specified schema and context
///
/// This is a simple wrapper around the `execute_sync` function exposed at the
Expand Down
5 changes: 3 additions & 2 deletions juniper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,12 @@ pub use crate::util::to_camel_case;
use crate::{
executor::{execute_validated_query, get_operation},
introspection::{INTROSPECTION_QUERY, INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS},
parser::{parse_document_source, ParseError, Spanning},
parser::parse_document_source,
validation::{validate_input_values, visit_all_rules, ValidatorContext},
};

pub use crate::{
ast::{FromInputValue, InputValue, Selection, ToInputValue, Type},
ast::{Document, FromInputValue, InputValue, Selection, ToInputValue, Type},
executor::{
Applies, Context, ExecutionError, ExecutionResult, Executor, FieldError, FieldResult,
FromContext, IntoFieldError, IntoResolvable, LookAheadArgument, LookAheadMethods,
Expand All @@ -179,6 +179,7 @@ pub use crate::{
subscription::{ExtractTypeFromStream, IntoFieldResult},
AsDynGraphQLValue,
},
parser::{ParseError, Spanning},
schema::{
meta,
model::{RootNode, SchemaType},
Expand Down