Run cargo fmt

This commit is contained in:
Daniel Wiesenberg 2020-09-04 11:50:24 +02:00
parent 258f379a51
commit f06341eda0
No known key found for this signature in database
GPG Key ID: A3BC00FBB8EDFCBF

View File

@ -4,22 +4,23 @@
#![forbid(unsafe_code)] #![forbid(unsafe_code)]
use async_graphql::{ use async_graphql::{
IntoQueryBuilder, IntoQueryBuilderOpts, QueryBuilder, QueryResponse, Schema, Variables, ObjectType, SubscriptionType IntoQueryBuilder, IntoQueryBuilderOpts, ObjectType, QueryBuilder, QueryResponse, Schema,
SubscriptionType, Variables,
}; };
use log::{error, info}; use log::{error, info};
use rocket::{ use rocket::{
Request, Response, State, data::{self, FromData},
data::{Data, ToByteUnit}, data::{Data, ToByteUnit},
fairing::{AdHoc, Fairing}, fairing::{AdHoc, Fairing},
http::{ContentType, Header, Status, hyper::header::CACHE_CONTROL}, http::{hyper::header::CACHE_CONTROL, ContentType, Header, Status},
request::{self, FromQuery, Outcome}, request::{self, FromQuery, Outcome},
response::{self, Responder, ResponseBuilder}, data::{self, FromData} response::{self, Responder, ResponseBuilder},
Request, Response, State,
}; };
use std::{io::Cursor, sync::Arc}; use std::{io::Cursor, sync::Arc};
use tokio_util::compat::Tokio02AsyncReadCompatExt; use tokio_util::compat::Tokio02AsyncReadCompatExt;
use yansi::Paint; use yansi::Paint;
/// Contains the fairing functions, to attach GraphQL with the desired `Schema`, and optionally /// Contains the fairing functions, to attach GraphQL with the desired `Schema`, and optionally
/// `QueryBuilderOpts`, to Rocket. /// `QueryBuilderOpts`, to Rocket.
/// ///
@ -65,8 +66,7 @@ use yansi::Paint;
/// ``` /// ```
pub struct GraphQL; pub struct GraphQL;
impl GraphQL impl GraphQL {
{
/// Fairing with default `QueryBuilderOpts`. You just need to pass in your `Schema` and then can /// Fairing with default `QueryBuilderOpts`. You just need to pass in your `Schema` and then can
/// attach the `Fairing` to Rocket. /// attach the `Fairing` to Rocket.
/// ///
@ -81,7 +81,7 @@ impl GraphQL
where where
Q: ObjectType + Send + Sync + 'static, Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static, M: ObjectType + Send + Sync + 'static,
S: SubscriptionType + Send + Sync + 'static S: SubscriptionType + Send + Sync + 'static,
{ {
GraphQL::attach(schema, Default::default()) GraphQL::attach(schema, Default::default())
} }
@ -97,11 +97,14 @@ impl GraphQL
/// .attach(GraphQL::fairing_with_opts(schema, opts)) /// .attach(GraphQL::fairing_with_opts(schema, opts))
/// .mount("/", routes![graphql_query, graphql_request]) /// .mount("/", routes![graphql_query, graphql_request])
/// ``` /// ```
pub fn fairing_with_opts<Q, M, S>(schema: Schema<Q, M, S>, opts: IntoQueryBuilderOpts) -> impl Fairing pub fn fairing_with_opts<Q, M, S>(
schema: Schema<Q, M, S>,
opts: IntoQueryBuilderOpts,
) -> impl Fairing
where where
Q: ObjectType + Send + Sync + 'static, Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static, M: ObjectType + Send + Sync + 'static,
S: SubscriptionType + Send + Sync + 'static S: SubscriptionType + Send + Sync + 'static,
{ {
GraphQL::attach(schema, opts) GraphQL::attach(schema, opts)
} }
@ -110,15 +113,17 @@ impl GraphQL
where where
Q: ObjectType + Send + Sync + 'static, Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static, M: ObjectType + Send + Sync + 'static,
S: SubscriptionType + Send + Sync + 'static S: SubscriptionType + Send + Sync + 'static,
{ {
AdHoc::on_attach("GraphQL", move |rocket| async move { AdHoc::on_attach("GraphQL", move |rocket| async move {
let emoji = if cfg!(windows) {""} else {"📄 "}; let emoji = if cfg!(windows) { "" } else { "📄 " };
info!("{}{}", Paint::masked(emoji), Paint::magenta(format!("GraphQL {}:", Paint::blue(""))).wrap()); info!(
"{}{}",
Paint::masked(emoji),
Paint::magenta(format!("GraphQL {}:", Paint::blue(""))).wrap()
);
Ok(rocket.manage(schema) Ok(rocket.manage(schema).manage(Arc::new(opts)))
.manage(Arc::new(opts))
)
}) })
} }
} }
@ -150,15 +155,12 @@ impl GQLRequest {
where where
Q: ObjectType + Send + Sync + 'static, Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static, M: ObjectType + Send + Sync + 'static,
S: SubscriptionType + Send + Sync + 'static S: SubscriptionType + Send + Sync + 'static,
{ {
self.0.execute(schema) self.0.execute(schema).await.map(GQLResponse).map_err(|e| {
.await error!("{}", e);
.map(GQLResponse) Status::BadRequest
.map_err(|e| { })
error!("{}", e);
Status::BadRequest
})
} }
} }
@ -177,26 +179,21 @@ impl<'q> FromQuery<'q> for GQLRequest {
if query.is_some() { if query.is_some() {
return Err(r#"Multiple parameters named "query" found. Only one parameter by that name is allowed."#.to_string()); return Err(r#"Multiple parameters named "query" found. Only one parameter by that name is allowed."#.to_string());
} else { } else {
query = value.url_decode() query = value.url_decode().map_err(|e| e.to_string())?.into();
.map_err(|e| e.to_string())?
.into();
} }
} }
"operation_name" => { "operation_name" => {
if operation_name.is_some() { if operation_name.is_some() {
return Err(r#"Multiple parameters named "operation_name" found. Only one parameter by that name is allowed."#.to_string()); return Err(r#"Multiple parameters named "operation_name" found. Only one parameter by that name is allowed."#.to_string());
} else { } else {
operation_name = value.url_decode() operation_name = value.url_decode().map_err(|e| e.to_string())?.into();
.map_err(|e| e.to_string())?
.into();
} }
} }
"variables" => { "variables" => {
if variables.is_some() { if variables.is_some() {
return Err(r#"Multiple parameters named "variables" found. Only one parameter by that name is allowed."#.to_string()); return Err(r#"Multiple parameters named "variables" found. Only one parameter by that name is allowed."#.to_string());
} else { } else {
let decoded= value.url_decode() let decoded = value.url_decode().map_err(|e| e.to_string())?;
.map_err(|e| e.to_string())?;
let json_value = serde_json::from_str::<serde_json::Value>(&decoded) let json_value = serde_json::from_str::<serde_json::Value>(&decoded)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
variables = Variables::parse_from_json(json_value) variables = Variables::parse_from_json(json_value)
@ -205,7 +202,10 @@ impl<'q> FromQuery<'q> for GQLRequest {
} }
} }
_ => { _ => {
return Err(format!(r#"Extra parameter named "{}" found. Extra parameters are not allowed."#, key)); return Err(format!(
r#"Extra parameter named "{}" found. Extra parameters are not allowed."#,
key
));
} }
} }
} }
@ -235,7 +235,12 @@ impl FromData for GQLRequest {
async fn from_data(req: &Request<'_>, data: Data) -> data::Outcome<Self, Self::Error> { async fn from_data(req: &Request<'_>, data: Data) -> data::Outcome<Self, Self::Error> {
let opts = match req.guard::<State<'_, Arc<IntoQueryBuilderOpts>>>().await { let opts = match req.guard::<State<'_, Arc<IntoQueryBuilderOpts>>>().await {
Outcome::Success(opts) => opts, Outcome::Success(opts) => opts,
Outcome::Failure(_) => return data::Outcome::Failure((Status::InternalServerError, "Missing IntoQueryBuilderOpts in State".to_string())), Outcome::Failure(_) => {
return data::Outcome::Failure((
Status::InternalServerError,
"Missing IntoQueryBuilderOpts in State".to_string(),
))
}
Outcome::Forward(()) => unreachable!(), Outcome::Forward(()) => unreachable!(),
}; };
@ -272,17 +277,21 @@ impl<'r> Responder<'r, 'static> for GQLResponse {
} }
/// Extension trait, to allow the use of `cache_control` with for example `ResponseBuilder`. /// Extension trait, to allow the use of `cache_control` with for example `ResponseBuilder`.
pub trait CacheControl{ pub trait CacheControl {
/// Add the `async-graphql::query::QueryResponse` cache control value as header to the Rocket response. /// Add the `async-graphql::query::QueryResponse` cache control value as header to the Rocket response.
fn cache_control(&mut self, resp: &async_graphql::Result<QueryResponse>) -> &mut Self; fn cache_control(&mut self, resp: &async_graphql::Result<QueryResponse>) -> &mut Self;
} }
impl<'r> CacheControl for ResponseBuilder<'r> { impl<'r> CacheControl for ResponseBuilder<'r> {
fn cache_control(&mut self, resp: &async_graphql::Result<QueryResponse>) -> &mut ResponseBuilder<'r> { fn cache_control(
&mut self,
resp: &async_graphql::Result<QueryResponse>,
) -> &mut ResponseBuilder<'r> {
match resp { match resp {
Ok(resp) if resp.cache_control.value().is_some() => { Ok(resp) if resp.cache_control.value().is_some() => self.header(Header::new(
self.header(Header::new(CACHE_CONTROL.as_str(), resp.cache_control.value().unwrap())) CACHE_CONTROL.as_str(),
} resp.cache_control.value().unwrap(),
)),
_ => self, _ => self,
} }
} }