use crate::error::Result;
pub trait BuildableSelector {
const DEFAULT_COMPLEXITY: u32 = 1;
fn build(&self) -> String;
fn root_complexity(&self) -> u32 {
Self::DEFAULT_COMPLEXITY
}
fn fields_complexity(&self) -> u32;
fn complexity(&self) -> u32 {
self.root_complexity() + self.fields_complexity()
}
fn depth(&self) -> u32;
}
pub trait IntoSelectorClosure<T: BuildableSelector + Default> {
fn evaluate_selection(self) -> (String, u32, u32);
}
impl<T, F, S> IntoSelectorClosure<T> for F
where
T: BuildableSelector + Default,
F: FnOnce(T) -> S,
S: BuildableSelector,
{
fn evaluate_selection(self) -> (String, u32, u32) {
let initial = T::default();
let built = self(initial);
(built.build(), built.fields_complexity(), built.depth())
}
}
impl<T: BuildableSelector + Default> IntoSelectorClosure<T> for () {
fn evaluate_selection(self) -> (String, u32, u32) {
let initial = T::default();
(
initial.build(),
initial.fields_complexity(),
initial.depth(),
)
}
}
impl<T, F, S> IntoSelectorClosure<T> for Option<F>
where
T: BuildableSelector + Default,
F: FnOnce(T) -> S,
S: BuildableSelector,
{
fn evaluate_selection(self) -> (String, u32, u32) {
match self {
Some(f) => {
let initial = T::default();
let built = f(initial);
(built.build(), built.fields_complexity(), built.depth())
}
None => {
let initial = T::default();
(
initial.build(),
initial.fields_complexity(),
initial.depth(),
)
}
}
}
}
pub trait GqlInspectable {
fn complexity(&self) -> u32;
fn depth(&self) -> u32;
fn max_complexity(&self) -> Option<u32> {
None
}
fn max_depth(&self) -> Option<u32> {
None
}
}
pub trait GqlValidatable {
fn validate_args(&self) -> Result<()>;
}
#[diagnostic::on_unimplemented(
message = "GraphQL query `{Self}` is missing required argument(s)",
label = "required argument missing",
note = "call all `#[validate(required)]` arguments on the builder"
)]
pub trait BuildableQuery: GqlInspectable + GqlValidatable {
fn _build_query_parts(
&self,
use_variables: bool,
) -> (
String,
Vec<String>,
serde_json::Map<String, serde_json::Value>,
);
fn _build_query(&self) -> String {
let (q, _, _) = self._build_query_parts(false);
format!("query {{ {} }}", q)
}
}
pub trait CompositeQueryDocument: GqlInspectable + GqlValidatable + Default {
fn use_variables(&mut self, enable: bool) -> &mut Self;
fn build_payload_details(
&self,
) -> (
Vec<String>,
Vec<String>,
serde_json::Map<String, serde_json::Value>,
);
fn build_payload_parts(&self) -> (String, Option<serde_json::Value>) {
let (root_queries, all_decls, all_vars) = self.build_payload_details();
let query_body = if root_queries.is_empty() {
String::new()
} else {
root_queries.join(" ")
};
let final_query = if !all_decls.is_empty() {
format!("query ({}) {{ {} }}", all_decls.join(", "), query_body)
} else {
format!("query {{ {} }}", query_body)
};
let final_vars = if all_vars.is_empty() {
None
} else {
Some(serde_json::Value::Object(all_vars))
};
(final_query, final_vars)
}
}