async-graphql/integrations/poem/src/extractor.rs

91 lines
2.6 KiB
Rust
Raw Normal View History

2021-08-23 15:16:31 +00:00
use async_graphql::http::MultipartOptions;
2022-04-19 04:25:11 +00:00
use poem::{
async_trait,
error::BadRequest,
http::{header, Method},
web::Query,
FromRequest, Request, RequestBody, Result,
};
2021-08-23 15:16:31 +00:00
use tokio_util::compat::TokioAsyncReadCompatExt;
/// An extractor for GraphQL request.
///
2022-04-19 04:25:11 +00:00
/// You can just use the extractor as in the example below, but I would
/// recommend using the [`GraphQL`](crate::GraphQL) endpoint because it is
/// easier to integrate.
2021-08-23 15:16:31 +00:00
///
/// # Example
///
/// ```
/// use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};
2022-04-19 04:25:11 +00:00
/// use async_graphql_poem::GraphQLRequest;
/// use poem::{
/// handler,
/// middleware::AddData,
/// post,
/// web::{Data, Json},
/// EndpointExt, Route,
/// };
2021-08-23 15:16:31 +00:00
///
/// struct Query;
///
/// #[Object]
/// impl Query {
/// async fn value(&self) -> i32 {
/// 100
/// }
/// }
///
/// type MySchema = Schema<Query, EmptyMutation, EmptySubscription>;
///
2021-09-01 00:15:27 +00:00
/// #[handler]
2021-08-23 15:16:31 +00:00
/// async fn index(req: GraphQLRequest, schema: Data<&MySchema>) -> Json<async_graphql::Response> {
/// Json(schema.execute(req.0).await)
/// }
///
2021-09-01 00:15:27 +00:00
/// let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
2021-10-23 05:33:21 +00:00
/// let app = Route::new().at("/", post(index.with(AddData::new(schema))));
2021-08-23 15:16:31 +00:00
/// ```
pub struct GraphQLRequest(pub async_graphql::Request);
#[async_trait]
impl<'a> FromRequest<'a> for GraphQLRequest {
async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
Ok(GraphQLRequest(
GraphQLBatchRequest::from_request(req, body)
.await?
.0
.into_single()
2021-10-27 05:57:05 +00:00
.map_err(BadRequest)?,
2021-08-23 15:16:31 +00:00
))
}
}
/// An extractor for GraphQL batch request.
pub struct GraphQLBatchRequest(pub async_graphql::BatchRequest);
#[async_trait]
impl<'a> FromRequest<'a> for GraphQLBatchRequest {
async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
if req.method() == Method::GET {
2021-10-27 12:06:33 +00:00
let req = Query::from_request(req, body).await?.0;
2021-08-23 15:16:31 +00:00
Ok(Self(async_graphql::BatchRequest::Single(req)))
} else {
let content_type = req
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(ToString::to_string);
Ok(Self(
async_graphql::http::receive_batch_body(
content_type,
body.take()?.into_async_read().compat(),
MultipartOptions::default(),
)
2021-12-16 04:56:11 +00:00
.await
.map_err(BadRequest)?,
2021-08-23 15:16:31 +00:00
))
}
}
}