async-graphql/src/http/mod.rs

48 lines
1.5 KiB
Rust
Raw Normal View History

2020-03-26 03:34:28 +00:00
//! A helper module that supports HTTP
2020-03-05 00:39:56 +00:00
mod graphiql_source;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "multipart")]
mod multipart;
2020-03-05 00:39:56 +00:00
mod playground_source;
mod websocket;
2020-03-05 00:39:56 +00:00
pub use graphiql_source::graphiql_source;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "multipart")]
pub use multipart::{receive_multipart, MultipartOptions};
pub use playground_source::{playground_source, GraphQLPlaygroundConfig};
pub use websocket::WebSocketStream;
2020-03-05 00:39:56 +00:00
2020-09-12 16:07:46 +00:00
use crate::{ParseRequestError, Request};
2020-09-10 07:04:24 +00:00
use futures::io::AsyncRead;
use futures::AsyncReadExt;
2020-09-10 08:54:38 +00:00
2020-09-10 07:04:24 +00:00
/// Receive a GraphQL request from a content type and body.
2020-09-14 19:16:41 +00:00
///
/// If the content type is multipart it will use `receive_multipart`, otherwise it will use
/// `receive_json`.
#[cfg(feature = "multipart")]
2020-09-15 18:32:13 +00:00
#[cfg_attr(feature = "nightly", doc(cfg(feature = "multipart")))]
2020-09-10 07:04:24 +00:00
pub async fn receive_body(
content_type: Option<impl AsRef<str>>,
body: impl AsyncRead + Send + 'static,
2020-09-10 07:04:24 +00:00
opts: MultipartOptions,
2020-09-10 08:54:38 +00:00
) -> Result<Request, ParseRequestError> {
2020-09-10 07:04:24 +00:00
if let Some(Ok(boundary)) = content_type.map(multer::parse_boundary) {
2020-09-14 19:16:41 +00:00
receive_multipart(body, boundary, opts).await
} else {
receive_json(body).await
2020-03-05 00:39:56 +00:00
}
2020-09-14 19:16:41 +00:00
}
2020-09-14 18:38:41 +00:00
2020-09-14 19:16:41 +00:00
/// Receive a GraphQL request from a body as JSON.
2020-09-14 19:20:15 +00:00
pub async fn receive_json(
body: impl AsyncRead + Send + 'static,
) -> Result<Request, ParseRequestError> {
2020-09-14 18:38:41 +00:00
let mut data = Vec::new();
futures::pin_mut!(body);
body.read_to_end(&mut data)
.await
.map_err(ParseRequestError::Io)?;
Ok(serde_json::from_slice::<Request>(&data).map_err(ParseRequestError::InvalidRequest)?)
2020-03-05 00:39:56 +00:00
}