2022-04-08 09:44:50 -05:00
|
|
|
#![doc = include_str!("../README.md")]
|
2018-09-24 05:07:44 -05:00
|
|
|
|
2020-10-19 11:42:27 -05:00
|
|
|
use std::{error::Error, fmt, string::FromUtf8Error, sync::Arc};
|
2018-09-01 22:02:01 -05:00
|
|
|
|
2023-11-17 07:04:37 -06:00
|
|
|
use http_body_util::BodyExt as _;
|
2019-08-21 08:23:53 -05:00
|
|
|
use hyper::{
|
2023-11-17 07:04:37 -06:00
|
|
|
body,
|
2019-08-21 08:23:53 -05:00
|
|
|
header::{self, HeaderValue},
|
2023-11-17 07:04:37 -06:00
|
|
|
Method, Request, Response, StatusCode,
|
2019-08-21 08:23:53 -05:00
|
|
|
};
|
|
|
|
use juniper::{
|
2020-05-08 11:00:49 -05:00
|
|
|
http::{GraphQLBatchRequest, GraphQLRequest as JuniperGraphQLRequest, GraphQLRequest},
|
2020-04-10 03:45:34 -05:00
|
|
|
GraphQLSubscriptionType, GraphQLType, GraphQLTypeAsync, InputValue, RootNode, ScalarValue,
|
2019-08-21 08:23:53 -05:00
|
|
|
};
|
2018-09-01 22:02:01 -05:00
|
|
|
use serde_json::error::Error as SerdeError;
|
|
|
|
use url::form_urlencoded;
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
pub async fn graphql_sync<CtxT, QueryT, MutationT, SubscriptionT, S>(
|
2020-03-20 11:11:06 -05:00
|
|
|
root_node: Arc<RootNode<'static, QueryT, MutationT, SubscriptionT, S>>,
|
2018-09-01 22:02:01 -05:00
|
|
|
context: Arc<CtxT>,
|
2023-11-17 07:04:37 -06:00
|
|
|
req: Request<body::Incoming>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Response<String>
|
2018-09-01 22:02:01 -05:00
|
|
|
where
|
2020-06-30 10:13:15 -05:00
|
|
|
QueryT: GraphQLType<S, Context = CtxT>,
|
|
|
|
QueryT::TypeInfo: Sync,
|
|
|
|
MutationT: GraphQLType<S, Context = CtxT>,
|
|
|
|
MutationT::TypeInfo: Sync,
|
|
|
|
SubscriptionT: GraphQLType<S, Context = CtxT>,
|
|
|
|
SubscriptionT::TypeInfo: Sync,
|
|
|
|
CtxT: Sync,
|
|
|
|
S: ScalarValue + Send + Sync,
|
2018-09-01 22:02:01 -05:00
|
|
|
{
|
2021-04-01 23:08:01 -05:00
|
|
|
match parse_req(req).await {
|
2020-05-08 11:00:49 -05:00
|
|
|
Ok(req) => execute_request_sync(root_node, context, req).await,
|
|
|
|
Err(resp) => resp,
|
2021-04-01 23:08:01 -05:00
|
|
|
}
|
2020-02-13 00:48:28 -06:00
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
pub async fn graphql<CtxT, QueryT, MutationT, SubscriptionT, S>(
|
2020-03-18 22:31:36 -05:00
|
|
|
root_node: Arc<RootNode<'static, QueryT, MutationT, SubscriptionT, S>>,
|
2020-02-13 00:48:28 -06:00
|
|
|
context: Arc<CtxT>,
|
2023-11-17 07:04:37 -06:00
|
|
|
req: Request<body::Incoming>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Response<String>
|
2020-02-13 00:48:28 -06:00
|
|
|
where
|
2020-06-30 10:13:15 -05:00
|
|
|
QueryT: GraphQLTypeAsync<S, Context = CtxT>,
|
|
|
|
QueryT::TypeInfo: Sync,
|
|
|
|
MutationT: GraphQLTypeAsync<S, Context = CtxT>,
|
|
|
|
MutationT::TypeInfo: Sync,
|
|
|
|
SubscriptionT: GraphQLSubscriptionType<S, Context = CtxT>,
|
|
|
|
SubscriptionT::TypeInfo: Sync,
|
|
|
|
CtxT: Sync,
|
|
|
|
S: ScalarValue + Send + Sync,
|
2020-02-13 00:48:28 -06:00
|
|
|
{
|
2021-04-01 23:08:01 -05:00
|
|
|
match parse_req(req).await {
|
2020-05-08 11:00:49 -05:00
|
|
|
Ok(req) => execute_request(root_node, context, req).await,
|
|
|
|
Err(resp) => resp,
|
2021-04-01 23:08:01 -05:00
|
|
|
}
|
2020-05-08 11:00:49 -05:00
|
|
|
}
|
2020-02-13 00:48:28 -06:00
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
async fn parse_req<S: ScalarValue>(
|
2023-11-17 07:04:37 -06:00
|
|
|
req: Request<body::Incoming>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Result<GraphQLBatchRequest<S>, Response<String>> {
|
2020-05-08 11:00:49 -05:00
|
|
|
match *req.method() {
|
|
|
|
Method::GET => parse_get_req(req),
|
2020-03-14 00:03:36 -05:00
|
|
|
Method::POST => {
|
2020-05-08 11:00:49 -05:00
|
|
|
let content_type = req
|
|
|
|
.headers()
|
|
|
|
.get(header::CONTENT_TYPE)
|
|
|
|
.map(HeaderValue::to_str);
|
|
|
|
match content_type {
|
|
|
|
Some(Ok("application/json")) => parse_post_json_req(req.into_body()).await,
|
|
|
|
Some(Ok("application/graphql")) => parse_post_graphql_req(req.into_body()).await,
|
|
|
|
_ => return Err(new_response(StatusCode::BAD_REQUEST)),
|
2020-02-13 00:48:28 -06:00
|
|
|
}
|
|
|
|
}
|
2020-05-08 11:00:49 -05:00
|
|
|
_ => return Err(new_response(StatusCode::METHOD_NOT_ALLOWED)),
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
2020-12-11 01:41:23 -06:00
|
|
|
.map_err(render_error)
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
|
|
|
|
2020-02-13 00:48:28 -06:00
|
|
|
fn parse_get_req<S: ScalarValue>(
|
2023-11-17 07:04:37 -06:00
|
|
|
req: Request<body::Incoming>,
|
2020-04-10 03:45:34 -05:00
|
|
|
) -> Result<GraphQLBatchRequest<S>, GraphQLRequestError> {
|
2020-02-13 00:48:28 -06:00
|
|
|
req.uri()
|
|
|
|
.query()
|
2020-04-10 03:45:34 -05:00
|
|
|
.map(|q| gql_request_from_get(q).map(GraphQLBatchRequest::Single))
|
2020-02-13 00:48:28 -06:00
|
|
|
.unwrap_or_else(|| {
|
|
|
|
Err(GraphQLRequestError::Invalid(
|
2022-07-13 05:30:51 -05:00
|
|
|
"'query' parameter is missing".into(),
|
2020-02-13 00:48:28 -06:00
|
|
|
))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
async fn parse_post_json_req<S: ScalarValue>(
|
2023-11-17 07:04:37 -06:00
|
|
|
body: body::Incoming,
|
2020-04-10 03:45:34 -05:00
|
|
|
) -> Result<GraphQLBatchRequest<S>, GraphQLRequestError> {
|
2023-11-17 07:04:37 -06:00
|
|
|
let chunk = body
|
|
|
|
.collect()
|
2020-02-13 00:48:28 -06:00
|
|
|
.await
|
2020-03-14 00:03:36 -05:00
|
|
|
.map_err(GraphQLRequestError::BodyHyper)?;
|
2020-02-13 00:48:28 -06:00
|
|
|
|
2023-11-17 07:04:37 -06:00
|
|
|
let input = String::from_utf8(chunk.to_bytes().iter().cloned().collect())
|
2020-02-13 00:48:28 -06:00
|
|
|
.map_err(GraphQLRequestError::BodyUtf8)?;
|
|
|
|
|
2020-04-10 03:45:34 -05:00
|
|
|
serde_json::from_str::<GraphQLBatchRequest<S>>(&input)
|
|
|
|
.map_err(GraphQLRequestError::BodyJSONError)
|
2020-02-13 00:48:28 -06:00
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
async fn parse_post_graphql_req<S: ScalarValue>(
|
2023-11-17 07:04:37 -06:00
|
|
|
body: body::Incoming,
|
2020-05-08 11:00:49 -05:00
|
|
|
) -> Result<GraphQLBatchRequest<S>, GraphQLRequestError> {
|
2023-11-17 07:04:37 -06:00
|
|
|
let chunk = body
|
|
|
|
.collect()
|
2020-05-08 11:00:49 -05:00
|
|
|
.await
|
|
|
|
.map_err(GraphQLRequestError::BodyHyper)?;
|
|
|
|
|
2023-11-17 07:04:37 -06:00
|
|
|
let query = String::from_utf8(chunk.to_bytes().iter().cloned().collect())
|
2020-05-08 11:00:49 -05:00
|
|
|
.map_err(GraphQLRequestError::BodyUtf8)?;
|
|
|
|
|
|
|
|
Ok(GraphQLBatchRequest::Single(GraphQLRequest::new(
|
|
|
|
query, None, None,
|
|
|
|
)))
|
|
|
|
}
|
|
|
|
|
2020-04-12 20:03:09 -05:00
|
|
|
pub async fn graphiql(
|
|
|
|
graphql_endpoint: &str,
|
|
|
|
subscriptions_endpoint: Option<&str>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Response<String> {
|
2018-09-01 22:02:01 -05:00
|
|
|
let mut resp = new_html_response(StatusCode::OK);
|
2018-09-30 13:07:44 -05:00
|
|
|
// XXX: is the call to graphiql_source blocking?
|
2022-09-19 10:59:33 -05:00
|
|
|
*resp.body_mut() =
|
|
|
|
juniper::http::graphiql::graphiql_source(graphql_endpoint, subscriptions_endpoint);
|
2021-04-01 23:08:01 -05:00
|
|
|
resp
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
|
|
|
|
2020-03-20 11:11:06 -05:00
|
|
|
pub async fn playground(
|
|
|
|
graphql_endpoint: &str,
|
|
|
|
subscriptions_endpoint: Option<&str>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Response<String> {
|
2019-01-25 22:58:01 -06:00
|
|
|
let mut resp = new_html_response(StatusCode::OK);
|
2022-09-19 10:59:33 -05:00
|
|
|
*resp.body_mut() =
|
|
|
|
juniper::http::playground::playground_source(graphql_endpoint, subscriptions_endpoint);
|
2021-04-01 23:08:01 -05:00
|
|
|
resp
|
2019-01-25 22:58:01 -06:00
|
|
|
}
|
|
|
|
|
2022-09-19 10:59:33 -05:00
|
|
|
fn render_error(err: GraphQLRequestError) -> Response<String> {
|
2018-09-01 22:02:01 -05:00
|
|
|
let mut resp = new_response(StatusCode::BAD_REQUEST);
|
2022-09-19 10:59:33 -05:00
|
|
|
*resp.body_mut() = err.to_string();
|
2018-09-01 22:02:01 -05:00
|
|
|
resp
|
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
async fn execute_request_sync<CtxT, QueryT, MutationT, SubscriptionT, S>(
|
2020-03-18 22:31:36 -05:00
|
|
|
root_node: Arc<RootNode<'static, QueryT, MutationT, SubscriptionT, S>>,
|
2018-09-01 22:02:01 -05:00
|
|
|
context: Arc<CtxT>,
|
2020-04-10 03:45:34 -05:00
|
|
|
request: GraphQLBatchRequest<S>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Response<String>
|
2018-09-01 22:02:01 -05:00
|
|
|
where
|
2020-06-30 10:13:15 -05:00
|
|
|
QueryT: GraphQLType<S, Context = CtxT>,
|
|
|
|
QueryT::TypeInfo: Sync,
|
|
|
|
MutationT: GraphQLType<S, Context = CtxT>,
|
|
|
|
MutationT::TypeInfo: Sync,
|
|
|
|
SubscriptionT: GraphQLType<S, Context = CtxT>,
|
|
|
|
SubscriptionT::TypeInfo: Sync,
|
|
|
|
CtxT: Sync,
|
|
|
|
S: ScalarValue + Send + Sync,
|
2018-09-01 22:02:01 -05:00
|
|
|
{
|
2020-04-10 03:45:34 -05:00
|
|
|
let res = request.execute_sync(&*root_node, &context);
|
2022-09-19 10:59:33 -05:00
|
|
|
let body = serde_json::to_string_pretty(&res).unwrap();
|
2020-04-10 03:45:34 -05:00
|
|
|
let code = if res.is_ok() {
|
2020-02-13 00:48:28 -06:00
|
|
|
StatusCode::OK
|
|
|
|
} else {
|
|
|
|
StatusCode::BAD_REQUEST
|
|
|
|
};
|
|
|
|
let mut resp = new_response(code);
|
|
|
|
resp.headers_mut().insert(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("application/json"),
|
|
|
|
);
|
|
|
|
*resp.body_mut() = body;
|
|
|
|
resp
|
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
async fn execute_request<CtxT, QueryT, MutationT, SubscriptionT, S>(
|
2020-03-18 22:31:36 -05:00
|
|
|
root_node: Arc<RootNode<'static, QueryT, MutationT, SubscriptionT, S>>,
|
2020-02-13 00:48:28 -06:00
|
|
|
context: Arc<CtxT>,
|
2020-04-10 03:45:34 -05:00
|
|
|
request: GraphQLBatchRequest<S>,
|
2022-09-19 10:59:33 -05:00
|
|
|
) -> Response<String>
|
2020-02-13 00:48:28 -06:00
|
|
|
where
|
2020-06-30 10:13:15 -05:00
|
|
|
QueryT: GraphQLTypeAsync<S, Context = CtxT>,
|
|
|
|
QueryT::TypeInfo: Sync,
|
|
|
|
MutationT: GraphQLTypeAsync<S, Context = CtxT>,
|
|
|
|
MutationT::TypeInfo: Sync,
|
|
|
|
SubscriptionT: GraphQLSubscriptionType<S, Context = CtxT>,
|
|
|
|
SubscriptionT::TypeInfo: Sync,
|
|
|
|
CtxT: Sync,
|
|
|
|
S: ScalarValue + Send + Sync,
|
2020-02-13 00:48:28 -06:00
|
|
|
{
|
2020-04-10 03:45:34 -05:00
|
|
|
let res = request.execute(&*root_node, &context).await;
|
2022-09-19 10:59:33 -05:00
|
|
|
let body = serde_json::to_string_pretty(&res).unwrap();
|
2020-04-10 03:45:34 -05:00
|
|
|
let code = if res.is_ok() {
|
2020-02-13 00:48:28 -06:00
|
|
|
StatusCode::OK
|
|
|
|
} else {
|
|
|
|
StatusCode::BAD_REQUEST
|
|
|
|
};
|
|
|
|
let mut resp = new_response(code);
|
|
|
|
resp.headers_mut().insert(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("application/json"),
|
|
|
|
);
|
|
|
|
*resp.body_mut() = body;
|
|
|
|
resp
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
|
|
|
|
Introduce an abstraction for scalar values (#251)
Introduce an abstraction for scalar values
Before this change, possible scalar values were hard coded to be representable
by one of the following types: `i32`, `f64`, `String` or `bool`. This
restricts the types of custom scalar values that can be defined. For
example, it was not possible to define a scalar value that represents an
`i64` without mapping it to a string (which would be inefficient).
One solution to fix the example above would simply be to change the
internal representation to allow it to represent an `i64`, but this would
only fix the problem for one type (until someone wants to support
`i128` for example). Also this would make juniper not follow the
GraphQL standard closely.
This commit takes another approach, by making the exact "internal"
representation of scalar values swappable (in such a way that a downstream crate could provide its own representation tailored to their needs). This allows juniper to provide a default type that only
contains the types described in the standard whereas other crates could define custom scalars for their needs.
To accomplish this we need to change several things in the current implementation:
* Add some traits that abstract the behavior of such a scalar value representation
* Change `Value` and `InputValue` to have a scalar variant (with a
generic type) instead of hard coded variants for the standard
types. This implies adding a generic parameter to both enums that
needs to be added in the whole crate.
* Change the parser to allow deciding between different types of
scalar values. The problem is basically that the original parser
implementation had no way to know whether a parsed integer number is
a `i32` or a `i64` (for example). To fix this we added some knowledge
of the existing schema to the parser.
* Fix some macros and derives to follow the new behavior.
This commit also contains an unrelated change about the way `juniper_codegen`
resolves items from `juniper`. The `_internal` flag is removed and
the resolution is replaced by a macro.
The scalar parsing strategy is as follows:
* Pass optional type information all the way down in the parser. If a
field/type/… does note exist, just do not pass down the type
information.
* The lexer now distinguishes between several fundamental scalar types (`String`, `Float`, `Int`). It does not try to actually parse those values, instead it just annotates them that this is a floating point number, an integer number, or a string value, etc.
* If type information exists while parsing a scalar value, try the following:
1. Try parsing the value using that type information.
2. If that fails try parsing the value using the inferred type information from the lexer.
* If no type information exists, try parsing the scalar value using the inferred type from the lexer,
All macros support the introduced scalar value abstraction. It is now possible to specify if a certain implementation should be based on a specific scalar value representation or be generic about the exact representation. All macros now default to the `DefaultScalarValue` type provided by
`juniper` if no scalar value representation is specified. This is done with usability and backwards compatibility in mind.
Finally, we allow specifying the scalar value representations via an attribute
(`#[graphql(scalar = "Type")]`). A default generic implementation
is provided.
2018-10-22 22:40:14 -05:00
|
|
|
fn gql_request_from_get<S>(input: &str) -> Result<JuniperGraphQLRequest<S>, GraphQLRequestError>
|
|
|
|
where
|
|
|
|
S: ScalarValue,
|
|
|
|
{
|
2018-09-01 22:02:01 -05:00
|
|
|
let mut query = None;
|
2023-09-12 07:45:56 -05:00
|
|
|
let mut operation_name = None;
|
2018-09-01 22:02:01 -05:00
|
|
|
let mut variables = None;
|
|
|
|
for (key, value) in form_urlencoded::parse(input.as_bytes()).into_owned() {
|
|
|
|
match key.as_ref() {
|
|
|
|
"query" => {
|
|
|
|
if query.is_some() {
|
|
|
|
return Err(invalid_err("query"));
|
|
|
|
}
|
|
|
|
query = Some(value)
|
|
|
|
}
|
|
|
|
"operationName" => {
|
|
|
|
if operation_name.is_some() {
|
|
|
|
return Err(invalid_err("operationName"));
|
|
|
|
}
|
2023-09-12 07:45:56 -05:00
|
|
|
operation_name = Some(value)
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
|
|
|
"variables" => {
|
|
|
|
if variables.is_some() {
|
|
|
|
return Err(invalid_err("variables"));
|
|
|
|
}
|
Introduce an abstraction for scalar values (#251)
Introduce an abstraction for scalar values
Before this change, possible scalar values were hard coded to be representable
by one of the following types: `i32`, `f64`, `String` or `bool`. This
restricts the types of custom scalar values that can be defined. For
example, it was not possible to define a scalar value that represents an
`i64` without mapping it to a string (which would be inefficient).
One solution to fix the example above would simply be to change the
internal representation to allow it to represent an `i64`, but this would
only fix the problem for one type (until someone wants to support
`i128` for example). Also this would make juniper not follow the
GraphQL standard closely.
This commit takes another approach, by making the exact "internal"
representation of scalar values swappable (in such a way that a downstream crate could provide its own representation tailored to their needs). This allows juniper to provide a default type that only
contains the types described in the standard whereas other crates could define custom scalars for their needs.
To accomplish this we need to change several things in the current implementation:
* Add some traits that abstract the behavior of such a scalar value representation
* Change `Value` and `InputValue` to have a scalar variant (with a
generic type) instead of hard coded variants for the standard
types. This implies adding a generic parameter to both enums that
needs to be added in the whole crate.
* Change the parser to allow deciding between different types of
scalar values. The problem is basically that the original parser
implementation had no way to know whether a parsed integer number is
a `i32` or a `i64` (for example). To fix this we added some knowledge
of the existing schema to the parser.
* Fix some macros and derives to follow the new behavior.
This commit also contains an unrelated change about the way `juniper_codegen`
resolves items from `juniper`. The `_internal` flag is removed and
the resolution is replaced by a macro.
The scalar parsing strategy is as follows:
* Pass optional type information all the way down in the parser. If a
field/type/… does note exist, just do not pass down the type
information.
* The lexer now distinguishes between several fundamental scalar types (`String`, `Float`, `Int`). It does not try to actually parse those values, instead it just annotates them that this is a floating point number, an integer number, or a string value, etc.
* If type information exists while parsing a scalar value, try the following:
1. Try parsing the value using that type information.
2. If that fails try parsing the value using the inferred type information from the lexer.
* If no type information exists, try parsing the scalar value using the inferred type from the lexer,
All macros support the introduced scalar value abstraction. It is now possible to specify if a certain implementation should be based on a specific scalar value representation or be generic about the exact representation. All macros now default to the `DefaultScalarValue` type provided by
`juniper` if no scalar value representation is specified. This is done with usability and backwards compatibility in mind.
Finally, we allow specifying the scalar value representations via an attribute
(`#[graphql(scalar = "Type")]`). A default generic implementation
is provided.
2018-10-22 22:40:14 -05:00
|
|
|
match serde_json::from_str::<InputValue<S>>(&value)
|
2018-09-01 22:02:01 -05:00
|
|
|
.map_err(GraphQLRequestError::Variables)
|
|
|
|
{
|
|
|
|
Ok(parsed_variables) => variables = Some(parsed_variables),
|
|
|
|
Err(e) => return Err(e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => continue,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
match query {
|
|
|
|
Some(query) => Ok(JuniperGraphQLRequest::new(query, operation_name, variables)),
|
|
|
|
None => Err(GraphQLRequestError::Invalid(
|
2022-07-13 05:30:51 -05:00
|
|
|
"'query' parameter is missing".into(),
|
2018-09-01 22:02:01 -05:00
|
|
|
)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn invalid_err(parameter_name: &str) -> GraphQLRequestError {
|
|
|
|
GraphQLRequestError::Invalid(format!(
|
2022-07-13 05:30:51 -05:00
|
|
|
"`{parameter_name}` parameter is specified multiple times",
|
2018-09-01 22:02:01 -05:00
|
|
|
))
|
|
|
|
}
|
|
|
|
|
2022-09-19 10:59:33 -05:00
|
|
|
fn new_response(code: StatusCode) -> Response<String> {
|
|
|
|
let mut r = Response::new(String::new());
|
2018-09-01 22:02:01 -05:00
|
|
|
*r.status_mut() = code;
|
|
|
|
r
|
|
|
|
}
|
|
|
|
|
2022-09-19 10:59:33 -05:00
|
|
|
fn new_html_response(code: StatusCode) -> Response<String> {
|
2018-09-01 22:02:01 -05:00
|
|
|
let mut resp = new_response(code);
|
|
|
|
resp.headers_mut().insert(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("text/html; charset=utf-8"),
|
|
|
|
);
|
|
|
|
resp
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
enum GraphQLRequestError {
|
|
|
|
BodyHyper(hyper::Error),
|
|
|
|
BodyUtf8(FromUtf8Error),
|
|
|
|
BodyJSONError(SerdeError),
|
|
|
|
Variables(SerdeError),
|
|
|
|
Invalid(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for GraphQLRequestError {
|
2022-01-26 12:58:53 -06:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match self {
|
|
|
|
GraphQLRequestError::BodyHyper(err) => fmt::Display::fmt(err, f),
|
|
|
|
GraphQLRequestError::BodyUtf8(err) => fmt::Display::fmt(err, f),
|
|
|
|
GraphQLRequestError::BodyJSONError(err) => fmt::Display::fmt(err, f),
|
|
|
|
GraphQLRequestError::Variables(err) => fmt::Display::fmt(err, f),
|
|
|
|
GraphQLRequestError::Invalid(err) => fmt::Display::fmt(err, f),
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Error for GraphQLRequestError {
|
2020-03-09 02:12:57 -05:00
|
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
2022-01-26 12:58:53 -06:00
|
|
|
match self {
|
|
|
|
GraphQLRequestError::BodyHyper(err) => Some(err),
|
|
|
|
GraphQLRequestError::BodyUtf8(err) => Some(err),
|
|
|
|
GraphQLRequestError::BodyJSONError(err) => Some(err),
|
|
|
|
GraphQLRequestError::Variables(err) => Some(err),
|
2018-09-01 22:02:01 -05:00
|
|
|
GraphQLRequestError::Invalid(_) => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-03-09 01:20:11 -05:00
|
|
|
|
2018-09-01 22:02:01 -05:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-11-17 07:04:37 -06:00
|
|
|
use std::{
|
|
|
|
convert::Infallible, error::Error, net::SocketAddr, panic, sync::Arc, time::Duration,
|
2019-08-21 08:23:53 -05:00
|
|
|
};
|
2023-11-17 07:04:37 -06:00
|
|
|
|
|
|
|
use hyper::{server::conn::http1, service::service_fn, Method, Response, StatusCode};
|
|
|
|
use hyper_util::rt::TokioIo;
|
2019-08-21 08:23:53 -05:00
|
|
|
use juniper::{
|
|
|
|
http::tests as http_tests,
|
Make interfaces great again! (#682)
* Bootstrap
* Upd
* Bootstrap macro
* Revert stuff
* Correct PoC to compile
* Bootstrap #[graphql_interface] expansion
* Bootstrap #[graphql_interface] meta parsing
* Bootstrap #[graphql_interface] very basic code generation [skip ci]
* Upd trait code generation and fix keywords usage [skip ci]
* Expand trait impls [skip ci]
* Tune up objects [skip ci]
* Finally! Complies at least... [skip ci]
* Parse meta for fields and its arguments [skip ci]
- also, refactor and bikeshed new macros code
* Impl filling fields meta and bootstrap field resolution [skip ci]
* Poking with fields resolution [skip ci]
* Solve Rust's teen async HRTB problems [skip ci]
* Start parsing trait methods [skip ci]
* Finish parsing fields from trait methods [skip ci]
* Autodetect trait asyncness and allow to specify it [skip ci]
* Allow to autogenerate trait object alias via attribute
* Support generics in trait definition and asyncify them correctly
* Temporary disable explicit async
* Cover arguments and custom names/descriptions in tests
* Re-enable tests with explicit async and fix the codegen to satisfy it
* Check implementers are registered in schema and vice versa
* Check argument camelCases
* Test argument defaults, and allow Into coercions for them
* Re-enable markers
* Re-enable markers and relax Sized requirement on IsInputType/IsOutputType marker traits
* Revert 'juniper_actix' fmt
* Fix missing marks for object
* Fix subscriptions marks
* Deduce result type correctly via traits
* Final fixes
* Fmt
* Restore marks checking
* Support custom ScalarValue
* Cover deprecations with tests
* Impl dowcasting via methods
* Impl dowcasting via external functions
* Support custom context, vol. 1
* Support custom context, vol. 2
* Cover fallible field with test
* Impl explicit generic ScalarValue, vol.1
* Impl explicit generic ScalarValue, vol.2
* Allow passing executor into methods
* Generating enum, vol.1
* Generating enum, vol.2
* Generating enum, vol.3
* Generating enum, vol.3
* Generating enum, vol.4
* Generating enum, vol.5
* Generating enum, vol.6
* Generating enum, vol.7
* Generating enum, vol.8
* Refactor juniper stuff
* Fix juniper tests, vol.1
* Fix juniper tests, vol.2
* Polish 'juniper' crate changes, vol.1
* Polish 'juniper' crate changes, vol.2
* Remove redundant stuf
* Polishing 'juniper_codegen', vol.1
* Polishing 'juniper_codegen', vol.2
* Polishing 'juniper_codegen', vol.3
* Polishing 'juniper_codegen', vol.4
* Polishing 'juniper_codegen', vol.5
* Polishing 'juniper_codegen', vol.6
* Polishing 'juniper_codegen', vol.7
* Polishing 'juniper_codegen', vol.8
* Polishing 'juniper_codegen', vol.9
* Fix other crates tests and make Clippy happier
* Fix examples
* Add codegen failure tests, vol. 1
* Add codegen failure tests, vol. 2
* Add codegen failure tests, vol.3
* Fix codegen failure tests accordingly to latest nightly Rust
* Fix codegen when interface has no implementers
* Fix warnings in book tests
* Describing new interfaces in Book, vol.1
Co-authored-by: Christian Legnitto <LegNeato@users.noreply.github.com>
2020-10-06 02:21:01 -05:00
|
|
|
tests::fixtures::starwars::schema::{Database, Query},
|
2020-03-18 22:31:36 -05:00
|
|
|
EmptyMutation, EmptySubscription, RootNode,
|
2019-08-21 08:23:53 -05:00
|
|
|
};
|
2023-11-17 07:04:37 -06:00
|
|
|
use reqwest::blocking::Response as ReqwestResponse;
|
|
|
|
use tokio::{net::TcpListener, task, time::sleep};
|
2018-09-01 22:02:01 -05:00
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
struct TestHyperIntegration {
|
|
|
|
port: u16,
|
|
|
|
}
|
2018-09-01 22:02:01 -05:00
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
impl http_tests::HttpIntegration for TestHyperIntegration {
|
2018-09-01 22:02:01 -05:00
|
|
|
fn get(&self, url: &str) -> http_tests::TestResponse {
|
2022-07-13 05:30:51 -05:00
|
|
|
let url = format!("http://127.0.0.1:{}/graphql{url}", self.port);
|
2023-08-25 17:48:01 -05:00
|
|
|
make_test_response(
|
|
|
|
reqwest::blocking::get(&url).unwrap_or_else(|_| panic!("failed GET {url}")),
|
|
|
|
)
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
fn post_json(&self, url: &str, body: &str) -> http_tests::TestResponse {
|
2022-07-13 05:30:51 -05:00
|
|
|
let url = format!("http://127.0.0.1:{}/graphql{url}", self.port);
|
2020-06-14 08:26:18 -05:00
|
|
|
let client = reqwest::blocking::Client::new();
|
2020-05-08 11:00:49 -05:00
|
|
|
let res = client
|
|
|
|
.post(&url)
|
|
|
|
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
2022-07-13 05:30:51 -05:00
|
|
|
.body(body.to_owned())
|
2020-05-08 11:00:49 -05:00
|
|
|
.send()
|
2023-08-25 17:48:01 -05:00
|
|
|
.unwrap_or_else(|_| panic!("failed POST {url}"));
|
2020-05-08 11:00:49 -05:00
|
|
|
make_test_response(res)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn post_graphql(&self, url: &str, body: &str) -> http_tests::TestResponse {
|
2022-07-13 05:30:51 -05:00
|
|
|
let url = format!("http://127.0.0.1:{}/graphql{url}", self.port);
|
2020-06-14 08:26:18 -05:00
|
|
|
let client = reqwest::blocking::Client::new();
|
2018-09-01 22:02:01 -05:00
|
|
|
let res = client
|
|
|
|
.post(&url)
|
2020-05-08 11:00:49 -05:00
|
|
|
.header(reqwest::header::CONTENT_TYPE, "application/graphql")
|
2022-07-13 05:30:51 -05:00
|
|
|
.body(body.to_owned())
|
2018-09-01 22:02:01 -05:00
|
|
|
.send()
|
2023-08-25 17:48:01 -05:00
|
|
|
.unwrap_or_else(|_| panic!("failed POST {url}"));
|
2018-09-01 22:02:01 -05:00
|
|
|
make_test_response(res)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-14 08:26:18 -05:00
|
|
|
fn make_test_response(response: ReqwestResponse) -> http_tests::TestResponse {
|
2018-09-01 22:02:01 -05:00
|
|
|
let status_code = response.status().as_u16() as i32;
|
2018-09-30 13:07:44 -05:00
|
|
|
let content_type_header = response.headers().get(reqwest::header::CONTENT_TYPE);
|
2022-07-13 05:30:51 -05:00
|
|
|
let content_type = content_type_header
|
|
|
|
.map(|ct| ct.to_str().unwrap().into())
|
|
|
|
.unwrap_or_default();
|
2020-06-14 08:26:18 -05:00
|
|
|
let body = response.text().unwrap();
|
2018-09-01 22:02:01 -05:00
|
|
|
|
|
|
|
http_tests::TestResponse {
|
|
|
|
status_code,
|
|
|
|
body: Some(body),
|
|
|
|
content_type,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-08 11:00:49 -05:00
|
|
|
async fn run_hyper_integration(is_sync: bool) {
|
|
|
|
let port = if is_sync { 3002 } else { 3001 };
|
2023-11-17 07:04:37 -06:00
|
|
|
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
2018-09-01 22:02:01 -05:00
|
|
|
|
|
|
|
let db = Arc::new(Database::new());
|
2020-03-18 22:31:36 -05:00
|
|
|
let root_node = Arc::new(RootNode::new(
|
|
|
|
Query,
|
|
|
|
EmptyMutation::<Database>::new(),
|
|
|
|
EmptySubscription::<Database>::new(),
|
|
|
|
));
|
2018-09-01 22:02:01 -05:00
|
|
|
|
2023-11-17 07:04:37 -06:00
|
|
|
let server: task::JoinHandle<Result<(), Box<dyn Error + Send + Sync>>> =
|
|
|
|
task::spawn(async move {
|
|
|
|
let listener = TcpListener::bind(addr).await?;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
let (stream, _) = listener.accept().await?;
|
|
|
|
let io = TokioIo::new(stream);
|
2020-02-13 00:48:28 -06:00
|
|
|
|
|
|
|
let root_node = root_node.clone();
|
2023-11-17 07:04:37 -06:00
|
|
|
let db = db.clone();
|
|
|
|
|
|
|
|
_ = task::spawn(async move {
|
|
|
|
let root_node = root_node.clone();
|
|
|
|
let db = db.clone();
|
|
|
|
|
|
|
|
if let Err(e) = http1::Builder::new()
|
|
|
|
.serve_connection(
|
|
|
|
io,
|
|
|
|
service_fn(move |req| {
|
|
|
|
let root_node = root_node.clone();
|
|
|
|
let db = db.clone();
|
|
|
|
let matches = {
|
|
|
|
let path = req.uri().path();
|
|
|
|
match req.method() {
|
|
|
|
&Method::POST | &Method::GET => {
|
|
|
|
path == "/graphql" || path == "/graphql/"
|
|
|
|
}
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
};
|
|
|
|
async move {
|
|
|
|
Ok::<_, Infallible>(if matches {
|
|
|
|
if is_sync {
|
|
|
|
super::graphql_sync(root_node, db, req).await
|
|
|
|
} else {
|
|
|
|
super::graphql(root_node, db, req).await
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let mut resp = Response::new(String::new());
|
|
|
|
*resp.status_mut() = StatusCode::NOT_FOUND;
|
|
|
|
resp
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
{
|
|
|
|
eprintln!("server error: {e}");
|
2020-02-13 00:48:28 -06:00
|
|
|
}
|
2023-11-17 07:04:37 -06:00
|
|
|
});
|
|
|
|
}
|
2020-02-13 00:48:28 -06:00
|
|
|
});
|
2018-09-01 22:02:01 -05:00
|
|
|
|
2023-11-17 07:04:37 -06:00
|
|
|
sleep(Duration::from_secs(10)).await; // wait 10ms for `server` to bind
|
|
|
|
|
|
|
|
match task::spawn_blocking(move || {
|
2020-05-08 11:00:49 -05:00
|
|
|
let integration = TestHyperIntegration { port };
|
2020-02-13 00:48:28 -06:00
|
|
|
http_tests::run_http_test_suite(&integration);
|
2023-11-17 07:04:37 -06:00
|
|
|
})
|
|
|
|
.await
|
|
|
|
{
|
|
|
|
Err(f) if f.is_panic() => panic::resume_unwind(f.into_panic()),
|
|
|
|
Ok(()) | Err(_) => {}
|
|
|
|
}
|
2018-09-01 22:02:01 -05:00
|
|
|
|
2023-11-17 07:04:37 -06:00
|
|
|
server.abort();
|
|
|
|
if let Ok(Err(e)) = server.await {
|
|
|
|
panic!("server failed: {e}");
|
2020-02-13 00:48:28 -06:00
|
|
|
}
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|
2020-05-08 11:00:49 -05:00
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_hyper_integration() {
|
|
|
|
run_hyper_integration(false).await
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_sync_hyper_integration() {
|
|
|
|
run_hyper_integration(true).await
|
|
|
|
}
|
2018-09-01 22:02:01 -05:00
|
|
|
}
|