async_graphql_warp/request.rs
1use async_graphql::{BatchRequest, Executor, Request, http::MultipartOptions};
2use warp::{Filter, Rejection, Reply, reply::Response as WarpResponse};
3
4use crate::{GraphQLBadRequest, GraphQLBatchResponse, graphql_batch_opts};
5
6/// GraphQL request filter
7///
8/// It outputs a tuple containing the `async_graphql::Schema` and
9/// `async_graphql::Request`.
10///
11/// # Examples
12///
13/// *[Full Example](<https://github.com/async-graphql/examples/blob/master/warp/starwars/src/main.rs>)*
14///
15/// ```no_run
16/// use std::convert::Infallible;
17///
18/// use async_graphql::*;
19/// use async_graphql_warp::*;
20/// use warp::Filter;
21///
22/// struct QueryRoot;
23///
24/// #[Object]
25/// impl QueryRoot {
26/// async fn value(&self, ctx: &Context<'_>) -> i32 {
27/// unimplemented!()
28/// }
29/// }
30///
31/// type MySchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
32///
33/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
34/// let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);
35/// let filter = async_graphql_warp::graphql(schema).and_then(
36/// |(schema, request): (MySchema, async_graphql::Request)| async move {
37/// Ok::<_, Infallible>(async_graphql_warp::GraphQLResponse::from(
38/// schema.execute(request).await,
39/// ))
40/// },
41/// );
42/// warp::serve(filter).run(([0, 0, 0, 0], 8000)).await;
43/// # });
44/// ```
45pub fn graphql<E>(
46 executor: E,
47) -> impl Filter<Extract = ((E, async_graphql::Request),), Error = Rejection> + Clone
48where
49 E: Executor,
50{
51 graphql_opts(executor, Default::default())
52}
53
54/// Similar to graphql, but you can set the options
55/// `async_graphql::MultipartOptions`.
56pub fn graphql_opts<E>(
57 executor: E,
58 opts: MultipartOptions,
59) -> impl Filter<Extract = ((E, Request),), Error = Rejection> + Clone
60where
61 E: Executor,
62{
63 graphql_batch_opts(executor, opts).and_then(|(schema, batch): (_, BatchRequest)| async move {
64 <Result<_, Rejection>>::Ok((
65 schema,
66 batch
67 .into_single()
68 .map_err(|e| warp::reject::custom(GraphQLBadRequest(e)))?,
69 ))
70 })
71}
72
73/// Reply for `async_graphql::Request`.
74#[derive(Debug)]
75pub struct GraphQLResponse(pub async_graphql::Response);
76
77impl From<async_graphql::Response> for GraphQLResponse {
78 fn from(resp: async_graphql::Response) -> Self {
79 GraphQLResponse(resp)
80 }
81}
82
83impl Reply for GraphQLResponse {
84 fn into_response(self) -> WarpResponse {
85 GraphQLBatchResponse(self.0.into()).into_response()
86 }
87}