async-graphql/integrations/axum/src/response.rs

54 lines
1.7 KiB
Rust
Raw Normal View History

2021-08-01 09:44:28 +00:00
use axum::body::Body;
2021-11-12 04:58:32 +00:00
use axum::http;
use axum::http::header::HeaderName;
use axum::http::{HeaderValue, Response};
2021-08-21 21:43:20 +00:00
use axum::response::IntoResponse;
2021-08-01 09:44:28 +00:00
/// Responder for a GraphQL response.
///
/// This contains a batch response, but since regular responses are a type of batch response it
/// works for both.
pub struct GraphQLResponse(pub async_graphql::BatchResponse);
impl From<async_graphql::Response> for GraphQLResponse {
fn from(resp: async_graphql::Response) -> Self {
Self(resp.into())
}
}
impl From<async_graphql::BatchResponse> for GraphQLResponse {
fn from(resp: async_graphql::BatchResponse) -> Self {
Self(resp)
}
}
impl IntoResponse for GraphQLResponse {
2021-08-21 21:43:20 +00:00
type Body = Body;
type BodyError = <Self::Body as axum::body::HttpBody>::Error;
2021-08-01 09:44:28 +00:00
fn into_response(self) -> Response<Body> {
let mut resp = Response::new(serde_json::to_string(&self.0).unwrap().into());
resp.headers_mut().insert(
http::header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
if self.0.is_ok() {
if let Some(cache_control) = self.0.cache_control().value() {
if let Ok(value) = HeaderValue::from_str(&cache_control) {
resp.headers_mut()
.insert(http::header::CACHE_CONTROL, value);
}
}
}
for (name, value) in self.0.http_headers() {
if let (Ok(name), Ok(value)) = (
HeaderName::try_from(name.as_bytes()),
HeaderValue::from_str(value),
) {
resp.headers_mut().insert(name, value);
}
}
resp
}
}