use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use super::{DeclaredError, ExchangeModel, MutationModel};
use crate::{emit::wire::wire_member, method::wire_method};
#[cfg(test)]
mod tests;
impl MutationModel {
#[must_use]
pub fn unit_name(&self) -> syn::Ident {
format_ident!("{}Mutations", self.name)
}
pub(super) fn wire(&self) -> TokenStream {
if self.graphql.is_empty() {
return TokenStream::new();
}
let unit = self.unit();
let face = self.face();
quote! {
#unit
#face
}
}
fn unit(&self) -> TokenStream {
let vis = &self.vis;
let name = self.unit_name();
let node = &self.name;
let doc = crate::emit::leading(&format!(
"The root fields a [`{node}`] answers — one per exchange it declared.\n\nMounted by folding \
it into a graph's root mutation; it holds nothing, and it reaches the source it controls \
through the command line the schema was built with."
));
quote! {
#[doc = #doc]
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::marker::Copy,
::core::default::Default,
)]
#vis struct #name;
}
}
fn face(&self) -> TokenStream {
let krate = &self.krate;
let name = self.unit_name();
let sdl = name.to_string();
let ag = crate::emit::framework(krate, &[], "async_graphql");
let shelf = crate::emit::vendored(krate, "async_graphql");
let gate = crate::emit::framework(krate, &["gate"], "if_async_graphql");
let prelude = crate::emit::wire::prelude();
let fields = self
.exchanges
.iter()
.map(|exchange| self.resolver(exchange));
quote! {
#gate! {
const _: () = {
#prelude
#[#ag::Object(crate = #shelf, name = #sdl)]
impl #name {
#(#fields)*
}
};
}
}
}
#[expect(
clippy::too_many_lines,
reason = "one resolver is one statement list, and the six steps the module note tabulates are \
exactly the six blocks below — splitting them into helpers would move the ORDER, \
which is the load-bearing part, out of the one place it can be read"
)]
fn resolver(&self, exchange: &ExchangeModel) -> TokenStream {
let krate = &self.krate;
let ag = crate::emit::framework(krate, &[], "async_graphql");
let mutation = crate::emit::framework(krate, &["source"], "Mutation");
let node = crate::emit::framework(krate, &["source"], "MutationNode");
let commands = crate::emit::framework(krate, &["source"], "Commands");
let shared = crate::emit::framework(krate, &["resource"], "Shared");
let refused = crate::emit::framework(krate, &["graphql"], "refused");
let refused_exchange = crate::emit::framework(krate, &["graphql"], "refused_exchange");
let unreachable = crate::emit::framework(krate, &["drive"], "QueryError");
let ty = &exchange.ty;
let name = &self.name;
let command = self.command_name();
let variant = exchange.variant();
let field = exchange.published();
let method = wire_method(&format_ident!("{}", exchange.named()));
let ctx = wire_method(&format_ident!("ctx"));
let input = wire_method(&format_ident!("input"));
let request = quote!(<#ty as #mutation>::Request);
let unit_answer = exchange.answers_nothing();
let response = if unit_answer {
quote!(::core::primitive::bool)
} else {
quote!(<#ty as #mutation>::Response)
};
let line = quote! {
let __ingraph_line = #ag::Context::data::<#commands<<#name as #node>::Command>>(#ctx)
.map_err(|_| #refused(&#unreachable::UnreachableSource))?;
};
let granted: Vec<syn::Ident> = (0..exchange.handler.context.len())
.map(|at| format_ident!("__ingraph_granted_{at}"))
.collect();
let grants = exchange
.handler
.context
.iter()
.zip(&granted)
.map(|(resource, held)| {
quote! {
let #held = #ag::Context::data::<#shared<#resource>>(#ctx)?;
}
});
let arguments = granted
.iter()
.zip(&exchange.handler.context)
.map(|(held, resource)| quote!(#shared::<#resource>::get(#held)));
let at = exchange.field.span();
let clone = quote_spanned!(at=> ::core::clone::Clone::clone(&#input));
let minted = quote! {
let __ingraph_command = #command::#variant(#clone);
};
let path = &exchange.handler.path;
let called = exchange.call_name();
let awaited = exchange.handler.awaited.then(|| quote!(.await));
let call = quote! {
#name::#called(#(#arguments,)* #input) #awaited
};
let (outcome, answer) = match &exchange.handler.error {
None => (
quote! {
let __ingraph_answer = #call;
},
quote!(__ingraph_answer),
),
Some(declared) => {
let render = match declared {
DeclaredError::Rich { code, .. } => {
let code = optional(code.as_ref());
quote!(#refused_exchange(#code, &__ingraph_refusal))
}
DeclaredError::Canned { message, code } => {
let code = optional(code.as_ref());
quote! {{
let () = __ingraph_refusal;
#refused_exchange(#code, #message)
}}
}
};
(
quote! {
let __ingraph_outcome = #call;
let __ingraph_answer = match __ingraph_outcome {
::core::result::Result::Ok(__ingraph_answer) => __ingraph_answer,
::core::result::Result::Err(__ingraph_refusal) => {
return ::core::result::Result::Err(#render);
}
};
},
quote!(__ingraph_answer),
)
}
};
let answered = if unit_answer {
quote! {
let () = #answer;
::core::result::Result::Ok(true)
}
} else {
quote!(::core::result::Result::Ok(#answer))
};
let doc = crate::emit::leading(&format!(
"The `{field}` exchange — validated and answered by `{handler}`, then applied by the source \
this node controls.",
handler = quote!(#path).to_string().replace(' ', ""),
));
quote! {
#[doc = #doc]
#[graphql(name = #field)]
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "input")] #input: #request,
) -> #ag::Result<#response> {
#line
#(#grants)*
#minted
#outcome
if #commands::say_async(__ingraph_line, __ingraph_command).await.is_err() {
return ::core::result::Result::Err(#refused(&#unreachable::UnreachableSource));
}
#answered
}
}
}
}
impl ExchangeModel {
#[must_use]
pub fn published(&self) -> String {
match &self.rename {
Some(rename) => rename.value(),
None => wire_member(&self.field),
}
}
fn answers_nothing(&self) -> bool {
let syn::Type::Tuple(pair) = &self.ty else {
return false;
};
matches!(
pair.elems.iter().collect::<Vec<_>>().as_slice(),
[_, syn::Type::Tuple(answer)] if answer.elems.is_empty()
)
}
}
fn optional(word: Option<&syn::LitStr>) -> TokenStream {
match word {
Some(word) => quote!(::core::option::Option::Some(#word)),
None => quote!(::core::option::Option::None),
}
}