async-graphql/integrations/rocket/src/lib.rs

300 lines
10 KiB
Rust
Raw Normal View History

2020-08-31 14:26:12 +00:00
//! Async-graphql integration with Rocket
#![warn(missing_docs)]
#![forbid(unsafe_code)]
2020-09-11 14:55:01 +00:00
use async_graphql::http::MultipartOptions;
2020-09-29 23:45:48 +00:00
use async_graphql::{ObjectType, Schema, SubscriptionType, Variables};
2020-08-31 14:26:12 +00:00
use log::{error, info};
use rocket::{
2020-09-04 09:50:24 +00:00
data::{self, FromData},
2020-08-31 14:26:12 +00:00
data::{Data, ToByteUnit},
fairing::{AdHoc, Fairing},
2020-09-04 10:01:16 +00:00
http::{ContentType, Header, Status},
2020-08-31 14:26:12 +00:00
request::{self, FromQuery, Outcome},
2020-09-04 09:50:24 +00:00
response::{self, Responder, ResponseBuilder},
2020-09-20 05:44:20 +00:00
Request as RocketRequest, Response as RocketResponse, State,
2020-08-31 14:26:12 +00:00
};
use std::{io::Cursor, sync::Arc};
use tokio_util::compat::Tokio02AsyncReadCompatExt;
use yansi::Paint;
2020-09-11 14:55:01 +00:00
/// Contains the fairing functions, to attach GraphQL with the desired `async_graphql::Schema`, and optionally
/// `async_graphql::MultipartOptions`, to Rocket.
2020-09-03 17:51:45 +00:00
///
/// # Examples
/// **[Full Example](<https://github.com/async-graphql/examples/blob/master/rocket/starwars/src/main.rs>)**
///
/// ```rust,no_run
///
/// use async_graphql::{EmptyMutation, EmptySubscription, Schema, Object};
2020-09-20 05:44:20 +00:00
/// use async_graphql_rocket::{Request, GraphQL, Response};
2020-09-03 17:51:45 +00:00
/// use rocket::{response::content, routes, State, http::Status};
///
/// type ExampleSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
/// struct QueryRoot;
///
/// #[Object]
2020-09-03 17:51:45 +00:00
/// impl QueryRoot {
2020-09-28 09:44:00 +00:00
/// /// Returns the sum of a and b
2020-09-03 17:51:45 +00:00
/// async fn add(&self, a: i32, b: i32) -> i32 {
/// a + b
/// }
/// }
///
/// #[rocket::post("/?<query..>")]
2020-09-20 05:44:20 +00:00
/// async fn graphql_query(schema: State<'_, ExampleSchema>, query: Request) -> Result<Response, Status> {
2020-09-03 17:51:45 +00:00
/// query.execute(&schema)
/// .await
/// }
///
/// #[rocket::post("/", data = "<request>", format = "application/json")]
2020-09-20 05:44:20 +00:00
/// async fn graphql_request(schema: State<'_, ExampleSchema>, request: Request) -> Result<Response, Status> {
2020-09-03 17:51:45 +00:00
/// request.execute(&schema)
/// .await
/// }
///
/// #[rocket::launch]
/// fn rocket() -> rocket::Rocket {
/// let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);
/// rocket::ignite()
/// .attach(GraphQL::fairing(schema))
/// .mount("/", routes![graphql_query, graphql_request])
/// }
/// ```
2020-08-31 14:26:12 +00:00
pub struct GraphQL;
2020-09-04 09:50:24 +00:00
impl GraphQL {
2020-09-11 14:55:01 +00:00
/// Fairing with default `async_graphql::MultipartOptions`. You just need to pass in your `async_graphql::Schema` and then can
2020-09-03 17:51:45 +00:00
/// attach the `Fairing` to Rocket.
///
/// # Examples
///
2020-09-04 10:48:41 +00:00
/// ```rust,no_run,ignore
2020-09-03 17:51:45 +00:00
/// rocket::ignite()
/// .attach(GraphQL::fairing(schema))
/// .mount("/", routes![graphql_query, graphql_request])
/// ```
2020-08-31 14:26:12 +00:00
pub fn fairing<Q, M, S>(schema: Schema<Q, M, S>) -> impl Fairing
where
Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static,
2020-09-04 09:50:24 +00:00
S: SubscriptionType + Send + Sync + 'static,
2020-08-31 14:26:12 +00:00
{
GraphQL::attach(schema, Default::default())
}
2020-09-11 14:55:01 +00:00
/// Fairing to which you need to pass `async_graphql::MultipartOptions` and your `async_graphql::Schema`. Then you can
2020-09-03 17:51:45 +00:00
/// attach the `Fairing` to Rocket.
///
/// # Examples
///
2020-09-04 10:48:41 +00:00
/// ```rust,no_run,ignore
2020-09-11 14:55:01 +00:00
/// let opts: MultipartOptions = Default::default();
2020-09-03 17:51:45 +00:00
/// rocket::ignite()
/// .attach(GraphQL::fairing_with_opts(schema, opts))
/// .mount("/", routes![graphql_query, graphql_request])
/// ```
2020-09-04 09:50:24 +00:00
pub fn fairing_with_opts<Q, M, S>(
schema: Schema<Q, M, S>,
2020-09-11 14:55:01 +00:00
opts: MultipartOptions,
2020-09-04 09:50:24 +00:00
) -> impl Fairing
2020-08-31 14:26:12 +00:00
where
Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static,
2020-09-04 09:50:24 +00:00
S: SubscriptionType + Send + Sync + 'static,
2020-08-31 14:26:12 +00:00
{
GraphQL::attach(schema, opts)
}
2020-09-11 14:55:01 +00:00
fn attach<Q, M, S>(schema: Schema<Q, M, S>, opts: MultipartOptions) -> impl Fairing
2020-08-31 14:26:12 +00:00
where
Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static,
2020-09-04 09:50:24 +00:00
S: SubscriptionType + Send + Sync + 'static,
2020-08-31 14:26:12 +00:00
{
AdHoc::on_attach("GraphQL", move |rocket| async move {
2020-09-04 09:50:24 +00:00
let emoji = if cfg!(windows) { "" } else { "📄 " };
info!(
"{}{}",
Paint::masked(emoji),
Paint::magenta(format!("GraphQL {}:", Paint::blue(""))).wrap()
);
2020-08-31 14:26:12 +00:00
2020-09-04 09:50:24 +00:00
Ok(rocket.manage(schema).manage(Arc::new(opts)))
2020-08-31 14:26:12 +00:00
})
}
}
2020-09-03 17:51:45 +00:00
/// Implements `FromQuery` and `FromData`, so that it can be used as parameter in a
/// Rocket route.
///
/// # Examples
///
2020-09-04 10:48:41 +00:00
/// ```rust,no_run,ignore
2020-09-03 17:51:45 +00:00
/// #[rocket::post("/?<query..>")]
2020-09-20 05:44:20 +00:00
/// async fn graphql_query(schema: State<'_, ExampleSchema>, query: Request) -> Result<Response, Status> {
2020-09-03 17:51:45 +00:00
/// query.execute(&schema)
/// .await
/// }
///
/// #[rocket::post("/", data = "<request>", format = "application/json")]
2020-09-20 05:44:20 +00:00
/// async fn graphql_request(schema: State<'_, ExampleSchema>, request: Request) -> Result<Response, Status> {
2020-09-03 17:51:45 +00:00
/// request.execute(&schema)
/// .await
/// }
/// ```
2020-09-20 05:44:20 +00:00
pub struct Request(pub async_graphql::Request);
2020-08-31 14:26:12 +00:00
2020-09-20 05:44:20 +00:00
impl Request {
2020-09-11 14:55:01 +00:00
/// Mimics `async_graphql::Schema.execute()`.
2020-09-03 17:51:45 +00:00
/// Executes the query, always return a complete result.
2020-09-20 05:44:20 +00:00
pub async fn execute<Q, M, S>(self, schema: &Schema<Q, M, S>) -> Result<Response, Status>
2020-08-31 14:26:12 +00:00
where
Q: ObjectType + Send + Sync + 'static,
M: ObjectType + Send + Sync + 'static,
2020-09-04 09:50:24 +00:00
S: SubscriptionType + Send + Sync + 'static,
2020-08-31 14:26:12 +00:00
{
2020-09-11 14:55:01 +00:00
schema
.execute(self.0)
.await
.into_result()
2020-09-20 05:44:20 +00:00
.map(Response)
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
.map_err(|es| {
for e in es {
error!("{}", e);
}
2020-09-11 14:55:01 +00:00
Status::BadRequest
})
2020-08-31 14:26:12 +00:00
}
}
2020-09-20 05:44:20 +00:00
impl<'q> FromQuery<'q> for Request {
2020-08-31 14:26:12 +00:00
type Error = String;
fn from_query(query_items: request::Query) -> Result<Self, Self::Error> {
let mut query = None;
let mut operation_name = None;
let mut variables = None;
for query_item in query_items {
let (key, value) = query_item.key_value();
match key.as_str() {
"query" => {
if query.is_some() {
2020-09-03 17:51:45 +00:00
return Err(r#"Multiple parameters named "query" found. Only one parameter by that name is allowed."#.to_string());
2020-08-31 14:26:12 +00:00
} else {
2020-09-04 09:50:24 +00:00
query = value.url_decode().map_err(|e| e.to_string())?.into();
2020-08-31 14:26:12 +00:00
}
}
"operation_name" => {
if operation_name.is_some() {
2020-09-03 17:51:45 +00:00
return Err(r#"Multiple parameters named "operation_name" found. Only one parameter by that name is allowed."#.to_string());
2020-08-31 14:26:12 +00:00
} else {
2020-09-04 09:50:24 +00:00
operation_name = value.url_decode().map_err(|e| e.to_string())?.into();
2020-08-31 14:26:12 +00:00
}
}
"variables" => {
if variables.is_some() {
2020-09-03 17:51:45 +00:00
return Err(r#"Multiple parameters named "variables" found. Only one parameter by that name is allowed."#.to_string());
2020-08-31 14:26:12 +00:00
} else {
2020-09-04 09:50:24 +00:00
let decoded = value.url_decode().map_err(|e| e.to_string())?;
2020-08-31 14:26:12 +00:00
let json_value = serde_json::from_str::<serde_json::Value>(&decoded)
.map_err(|e| e.to_string())?;
2020-09-12 16:07:46 +00:00
variables = Variables::from_json(json_value).into();
2020-08-31 14:26:12 +00:00
}
}
_ => {
2020-09-04 09:50:24 +00:00
return Err(format!(
r#"Extra parameter named "{}" found. Extra parameters are not allowed."#,
key
));
2020-08-31 14:26:12 +00:00
}
}
}
if let Some(query_source) = query {
2020-09-11 14:55:01 +00:00
let mut request = async_graphql::Request::new(query_source);
2020-08-31 14:26:12 +00:00
if let Some(variables) = variables {
2020-09-11 14:55:01 +00:00
request = request.variables(variables);
2020-08-31 14:26:12 +00:00
}
if let Some(operation_name) = operation_name {
2020-09-11 14:55:01 +00:00
request = request.operation_name(operation_name);
2020-08-31 14:26:12 +00:00
}
2020-09-20 05:44:20 +00:00
Ok(Request(request))
2020-08-31 14:26:12 +00:00
} else {
Err(r#"Parameter "query" missing from request."#.to_string())
}
}
}
#[rocket::async_trait]
2020-09-20 05:44:20 +00:00
impl FromData for Request {
2020-08-31 14:26:12 +00:00
type Error = String;
2020-09-20 05:44:20 +00:00
async fn from_data(req: &RocketRequest<'_>, data: Data) -> data::Outcome<Self, Self::Error> {
2020-09-11 14:55:01 +00:00
let opts = match req.guard::<State<'_, Arc<MultipartOptions>>>().await {
2020-08-31 14:26:12 +00:00
Outcome::Success(opts) => opts,
2020-09-04 09:50:24 +00:00
Outcome::Failure(_) => {
return data::Outcome::Failure((
Status::InternalServerError,
2020-09-11 15:38:18 +00:00
"Missing MultipartOptions in State".to_string(),
2020-09-04 09:50:24 +00:00
))
}
2020-08-31 14:26:12 +00:00
Outcome::Forward(()) => unreachable!(),
};
2020-09-03 17:51:45 +00:00
let limit = req.limits().get("graphql");
let stream = data.open(limit.unwrap_or_else(|| 128.kibibytes()));
2020-09-11 14:55:01 +00:00
let request = async_graphql::http::receive_body(
req.headers().get_one("Content-Type"),
stream.compat(),
MultipartOptions::clone(&opts),
)
.await;
2020-08-31 14:26:12 +00:00
2020-09-11 14:55:01 +00:00
match request {
2020-09-20 05:44:20 +00:00
Ok(request) => data::Outcome::Success(Request(request)),
2020-08-31 14:26:12 +00:00
Err(e) => data::Outcome::Failure((Status::BadRequest, format!("{}", e))),
}
}
}
2020-09-11 14:55:01 +00:00
/// Wrapper around `async-graphql::Response` for implementing the trait
2020-09-20 05:44:20 +00:00
/// `rocket::response::responder::Responder`, so that `Response` can directly be returned
2020-09-03 17:51:45 +00:00
/// from a Rocket Route function.
2020-09-20 05:44:20 +00:00
pub struct Response(pub async_graphql::Response);
2020-08-31 14:26:12 +00:00
2020-09-20 05:44:20 +00:00
impl<'r> Responder<'r, 'static> for Response {
fn respond_to(self, _: &'r RocketRequest<'_>) -> response::Result<'static> {
2020-09-11 14:55:01 +00:00
let body = serde_json::to_string(&self.0).unwrap();
2020-08-31 14:26:12 +00:00
2020-09-20 05:44:20 +00:00
RocketResponse::build()
2020-08-31 14:26:12 +00:00
.header(ContentType::new("application", "json"))
.status(Status::Ok)
.sized_body(body.len(), Cursor::new(body))
2020-09-11 14:55:01 +00:00
.cache_control(&self.0)
2020-08-31 14:26:12 +00:00
.ok()
}
}
2020-09-11 14:55:01 +00:00
/// Extension trait, to allow the use of `cache_control` with for example `async_graphql::Request`.
2020-09-04 09:50:24 +00:00
pub trait CacheControl {
2020-09-11 14:55:01 +00:00
/// Add the `async-graphql::Response` cache control value as header to the Rocket response.
fn cache_control(&mut self, resp: &async_graphql::Response) -> &mut Self;
2020-08-31 14:26:12 +00:00
}
impl<'r> CacheControl for ResponseBuilder<'r> {
2020-09-11 14:55:01 +00:00
fn cache_control(&mut self, resp: &async_graphql::Response) -> &mut ResponseBuilder<'r> {
if resp.is_ok() {
if let Some(value) = resp.cache_control.value() {
self.header(Header::new("cache-control", value));
}
2020-08-31 14:26:12 +00:00
}
2020-09-11 14:55:01 +00:00
self
2020-08-31 14:26:12 +00:00
}
}