use crate::error::Result;
use crate::payload::GraphQLPayload;
use crate::traits::{CompositeQueryDocument, GqlInspectable, GqlValidatable};
#[derive(Debug, Default, Clone)]
pub struct BatchDocumentBuilder<Q: CompositeQueryDocument> {
queries: Vec<Q>,
max_complexity_override: Option<u32>,
max_depth_override: Option<u32>,
use_variables: bool,
}
impl<Q: CompositeQueryDocument> BatchDocumentBuilder<Q> {
pub fn new() -> Self {
Self::default()
}
pub fn use_variables(&mut self, enable: bool) -> &mut Self {
self.use_variables = enable;
self
}
pub fn query<F>(&mut self, query_fn: F) -> &mut Self
where
F: FnOnce(&mut Q) -> &mut Q,
{
let mut q_builder = Q::default();
if self.use_variables {
q_builder.use_variables(true);
}
query_fn(&mut q_builder);
self.queries.push(q_builder);
self
}
pub fn with_max_complexity(&mut self, max: u32) -> &mut Self {
self.max_complexity_override = Some(max);
self
}
pub fn with_max_depth(&mut self, max: u32) -> &mut Self {
self.max_depth_override = Some(max);
self
}
pub fn max_complexity(&self) -> Option<u32> {
if let Some(max) = self.max_complexity_override {
return Some(max);
}
self.queries.iter().find_map(|q| q.max_complexity())
}
pub fn max_depth(&self) -> Option<u32> {
if let Some(max) = self.max_depth_override {
return Some(max);
}
self.queries.iter().find_map(|q| q.max_depth())
}
pub fn complexity(&self) -> u32 {
self.queries
.iter()
.map(|q| q.complexity())
.max()
.unwrap_or(0)
}
pub fn depth(&self) -> u32 {
self.queries.iter().map(|q| q.depth()).max().unwrap_or(1)
}
pub fn len(&self) -> usize {
self.queries.len()
}
pub fn is_empty(&self) -> bool {
self.queries.is_empty()
}
pub fn build_payloads(&self) -> Vec<GraphQLPayload> {
self.queries
.iter()
.map(|q| {
let (query, variables) = q.build_payload_parts();
GraphQLPayload {
operation_name: None,
query,
variables,
}
})
.collect()
}
#[doc(hidden)]
pub fn _build_payloads(&self) -> Vec<GraphQLPayload> {
self.build_payloads()
}
pub async fn execute_concurrent<F, Fut, T, E>(
&self,
executor: F,
) -> std::result::Result<Vec<T>, E>
where
F: Fn(GraphQLPayload) -> Fut,
Fut: std::future::Future<Output = std::result::Result<T, E>>,
{
let payloads = self.build_payloads();
let mut tasks = Vec::with_capacity(payloads.len());
for payload in payloads {
tasks.push(executor(payload));
}
let results = futures::future::join_all(tasks).await;
let mut responses = Vec::with_capacity(results.len());
for res in results {
responses.push(res?);
}
Ok(responses)
}
}
impl<Q: CompositeQueryDocument> GqlInspectable for BatchDocumentBuilder<Q> {
fn complexity(&self) -> u32 {
self.complexity()
}
fn depth(&self) -> u32 {
self.depth()
}
fn max_complexity(&self) -> Option<u32> {
self.max_complexity()
}
fn max_depth(&self) -> Option<u32> {
self.max_depth()
}
}
impl<Q: CompositeQueryDocument> GqlValidatable for BatchDocumentBuilder<Q> {
fn validate_args(&self) -> Result<()> {
for q in &self.queries {
q.validate_args()?;
}
Ok(())
}
}