async_graphql_viz/
response.rs

1use std::convert::TryFrom;
2
3use viz_core::{http, Response};
4use viz_utils::serde::json;
5
6/// Responder for a GraphQL response.
7///
8/// This contains a batch response, but since regular responses are a type of batch response it
9/// works for both.
10pub struct GraphQLResponse(pub async_graphql::BatchResponse);
11
12impl From<async_graphql::Response> for GraphQLResponse {
13    fn from(resp: async_graphql::Response) -> Self {
14        Self(resp.into())
15    }
16}
17
18impl From<async_graphql::BatchResponse> for GraphQLResponse {
19    fn from(resp: async_graphql::BatchResponse) -> Self {
20        Self(resp)
21    }
22}
23
24impl From<GraphQLResponse> for Response {
25    fn from(gr: GraphQLResponse) -> Self {
26        let mut resp = Response::json(Into::<String>::into(json::to_string(&gr.0).unwrap()));
27        if gr.0.is_ok() {
28            if let Some(cache_control) = gr.0.cache_control().value() {
29                if let Ok(value) = http::HeaderValue::from_str(&cache_control) {
30                    resp.headers_mut()
31                        .insert(http::header::CACHE_CONTROL, value);
32                }
33            }
34        }
35        for (name, value) in gr.0.http_headers() {
36            if let (Ok(name), Ok(value)) = (
37                http::header::HeaderName::try_from(name.as_bytes()),
38                http::HeaderValue::from_str(value),
39            ) {
40                resp.headers_mut().insert(name, value);
41            }
42        }
43        resp
44    }
45}