thegraph_graphql_http/http/request.rs
1use crate::graphql::{Document, IntoDocumentWithVariables};
2
3/// The media type for GraphQL-over-HTTP requests. As specified in the section
4/// [4.1 Media Types](https://graphql.github.io/graphql-over-http/draft/#sec-Media-Types)
5/// of the GraphQL-over-HTTP specification.
6pub const GRAPHQL_REQUEST_MEDIA_TYPE: &str = "application/json";
7
8/// The parameters of a GraphQL-over-HTTP request.
9///
10/// As specified in the section [5.1 Request Parameters](https://graphql.github.io/graphql-over-http/draft/#sec-Request-Parameters)
11/// of the GraphQL-over-HTTP specification.
12#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
13pub struct RequestParameters {
14 /// The string representation of the Source Text of a GraphQL Document as specified in [the
15 /// Language section of the GraphQL specification](https://spec.graphql.org/draft/#sec-Language).
16 pub query: Document,
17
18 /// Optional name of the operation in the Document to execute.
19 #[serde(rename = "operationName", skip_serializing_if = "Option::is_none")]
20 pub operation_name: Option<String>,
21
22 /// Values for any Variables defined by the Operation.
23 #[serde(skip_serializing_if = "serde_json::Map::is_empty")]
24 pub variables: serde_json::Map<String, serde_json::Value>,
25
26 /// Reserved for implementors to extend the protocol however they see fit.
27 #[serde(skip_serializing_if = "serde_json::Map::is_empty")]
28 pub extensions: serde_json::Map<String, serde_json::Value>,
29}
30
31/// Convert `self` into a `RequestParameters` struct.
32pub trait IntoRequestParameters {
33 /// Consumes `self` and returns a `RequestParameters` struct.
34 fn into_request_parameters(self) -> RequestParameters;
35}
36
37impl IntoRequestParameters for RequestParameters {
38 #[inline]
39 fn into_request_parameters(self) -> RequestParameters {
40 self
41 }
42}
43
44// Any type implementing `IntoDocumentWithVariables` (or `IntoDocument`) can be converted into
45// `RequestParameters`.
46impl<T> IntoRequestParameters for T
47where
48 T: IntoDocumentWithVariables,
49{
50 fn into_request_parameters(self) -> RequestParameters {
51 let (query, variables) = self.into_document_with_variables();
52
53 // Do not send the `variables` field if the json serialization fails, or if the
54 // serialization result is not a JSON object.
55 let variables = match serde_json::to_value(variables) {
56 Ok(serde_json::Value::Object(vars)) => Some(vars),
57 _ => None,
58 };
59
60 RequestParameters {
61 query,
62 operation_name: None,
63 variables: variables.unwrap_or_default(),
64 extensions: Default::default(),
65 }
66 }
67}