pub use graphql_client::{GraphQLQuery, Response};
pub use graphql_client::Error as GraphqlError;
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
struct GraphqlRequest {
query: String,
#[serde(skip_serializing_if = "Option::is_none")]
variables: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none", rename = "operationName")]
operation_name: Option<String>,
}
pub struct GraphqlRequestBuilder {
inner: crate::http::RequestBuilder,
query: String,
variables: Option<serde_json::Value>,
operation_name: Option<String>,
}
impl GraphqlRequestBuilder {
pub(crate) fn new(inner: crate::http::RequestBuilder) -> Self {
Self {
inner,
query: String::new(),
variables: None,
operation_name: None,
}
}
pub fn query(mut self, query: impl Into<String>) -> Self {
self.query = query.into();
self
}
pub fn variables(mut self, variables: serde_json::Value) -> Self {
self.variables = Some(variables);
self
}
pub fn operation_name(mut self, name: impl Into<String>) -> Self {
self.operation_name = Some(name.into());
self
}
pub fn typed_query<Q: GraphQLQuery>(mut self, variables: Q::Variables) -> Self
where
Q::Variables: Serialize,
{
let body = Q::build_query(variables);
self.query = body.query.to_string();
self.operation_name = Some(body.operation_name.to_string());
self.variables = serde_json::to_value(&body.variables).ok();
self
}
pub fn header<K, V>(mut self, key: K, value: V) -> Self
where
http::header::HeaderName: TryFrom<K>,
<http::header::HeaderName as TryFrom<K>>::Error: Into<http::Error>,
http::header::HeaderValue: TryFrom<V>,
<http::header::HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
{
self.inner = self.inner.header(key, value);
self
}
pub fn bearer_auth<T: std::fmt::Display>(mut self, token: T) -> Self {
self.inner = self.inner.bearer_auth(token);
self
}
pub fn basic_auth<U: std::fmt::Display, P: std::fmt::Display>(
mut self,
username: U,
password: Option<P>,
) -> Self {
self.inner = self.inner.basic_auth(username, password);
self
}
pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
self.inner = self.inner.timeout(timeout);
self
}
pub async fn send(self) -> Result<crate::http::Response, crate::http::Error> {
let gql_req = GraphqlRequest {
query: self.query,
variables: self.variables,
operation_name: self.operation_name,
};
self.inner.json(&gql_req).send().await
}
}