async_graphql_axum/
response.rs

1use axum::{
2    body::Body,
3    http,
4    http::HeaderValue,
5    response::{IntoResponse, Response},
6};
7
8/// Responder for a GraphQL response.
9///
10/// This contains a batch response, but since regular responses are a type of
11/// batch response it works for both.
12pub struct GraphQLResponse(pub async_graphql::BatchResponse);
13
14impl From<async_graphql::Response> for GraphQLResponse {
15    fn from(resp: async_graphql::Response) -> Self {
16        Self(resp.into())
17    }
18}
19
20impl From<async_graphql::BatchResponse> for GraphQLResponse {
21    fn from(resp: async_graphql::BatchResponse) -> Self {
22        Self(resp)
23    }
24}
25
26impl IntoResponse for GraphQLResponse {
27    fn into_response(self) -> Response {
28        let body: Body = serde_json::to_string(&self.0).unwrap().into();
29        let mut resp = Response::new(body);
30        resp.headers_mut().insert(
31            http::header::CONTENT_TYPE,
32            HeaderValue::from_static("application/graphql-response+json"),
33        );
34        if self.0.is_ok()
35            && let Some(cache_control) = self.0.cache_control().value()
36            && let Ok(value) = HeaderValue::from_str(&cache_control)
37        {
38            resp.headers_mut()
39                .insert(http::header::CACHE_CONTROL, value);
40        }
41
42        resp.headers_mut().extend(self.0.http_headers());
43        resp
44    }
45}