gurafi/expose.rs
1//! Exposing model fields without writing a resolver.
2//!
3//! Most object fields are a plain property of the model. [`expose!`] names the property once and
4//! derives the GraphQL field name and type from the Rust path:
5//!
6//! ```
7//! use gurafi::{Object, Schema, expose};
8//!
9//! #[derive(Object)]
10//! struct Giraffe {
11//! name: String,
12//! height: f32,
13//! }
14//!
15//! let mut schema = Schema::<()>::new();
16//! schema.object::<Giraffe>(|o| {
17//! o.expose(expose!(Giraffe::name));
18//! // Rename the GraphQL field while keeping the Rust path.
19//! o.expose(expose!(Giraffe::height as "heightMeters"));
20//! });
21//! schema.query(|q| {
22//! q.field("giraffe", |_: gurafi::NoArgs, _: &()| Giraffe {
23//! name: "Melman".into(),
24//! height: 3.4,
25//! });
26//! });
27//! ```
28//!
29//! Nested paths work as `expose!(Type::field.subfield)`, and every segment is cloned, so the
30//! model itself is never moved.
31//!
32//! The accessor is installed as a synchronous property resolver, so execution calls it inline
33//! instead of boxing a future per field. Options that need a future (authorization, validation or
34//! a `wrap_resolve` plugin) convert the field to the boxed path once, at build time; descriptors,
35//! type overrides and metadata keep the synchronous path.
36
37use std::sync::Arc;
38
39/// A model property exposed as a GraphQL field.
40///
41/// Construct it with `expose!`; it is consumed by
42/// [`ObjectBuilder::expose`](crate::ObjectBuilder::expose).
43pub struct Expose<M, T> {
44 name: &'static str,
45 get: Arc<dyn Fn(&M) -> T + Send + Sync>,
46}
47
48impl<M: 'static, T: 'static> Expose<M, T> {
49 /// Create an exposed field from its GraphQL name and an accessor.
50 pub fn new(name: &'static str, get: impl Fn(&M) -> T + Send + Sync + 'static) -> Self {
51 Self {
52 name,
53 get: Arc::new(get),
54 }
55 }
56
57 pub(crate) fn into_parts(self) -> (&'static str, Arc<dyn Fn(&M) -> T + Send + Sync>) {
58 (self.name, self.get)
59 }
60}
61
62impl<M, T> std::fmt::Debug for Expose<M, T> {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("Expose").field("name", &self.name).finish()
65 }
66}
67
68/// The last identifier in a `stringify!`-ed Rust path.
69///
70/// `stringify!(Giraffe::height)` is `"Giraffe :: height"`, so the GraphQL field name is the final
71/// identifier run.
72#[doc(hidden)]
73#[must_use]
74pub fn __expose_name(path: &'static str) -> &'static str {
75 fn is_ident_byte(byte: u8) -> bool {
76 byte == b'_' || byte.is_ascii_alphanumeric()
77 }
78
79 let bytes = path.as_bytes();
80 let mut end = bytes.len();
81 while end > 0 && !is_ident_byte(bytes[end - 1]) {
82 end -= 1;
83 }
84 let mut start = end;
85 while start > 0 && is_ident_byte(bytes[start - 1]) {
86 start -= 1;
87 }
88 &path[start..end]
89}
90
91/// Expose a model property as a GraphQL field.
92///
93/// The GraphQL field name defaults to the last path segment; the type is inferred from the
94/// property's Rust type. Forms:
95///
96/// - `expose!(Giraffe::name)` — field `name`.
97/// - `expose!(Giraffe::keeper::name)` — field `name`, reading `model.keeper.name`.
98/// - `expose!(Giraffe::height as "heightMeters")` — custom GraphQL name.
99///
100/// The generated accessor clones the final value, so the property's type must be `Clone`.
101#[macro_export]
102macro_rules! expose {
103 ($first:ident $(:: $rest:ident)+ as $name:literal) => {
104 $crate::Expose::new(
105 $name,
106 |__model: &$first| __model $(. $rest)+ .clone(),
107 )
108 };
109 ($first:ident $(:: $rest:ident)+) => {
110 $crate::Expose::new(
111 $crate::__expose_name(concat!(
112 stringify!($first)
113 $(, "::", stringify!($rest))*
114 )),
115 |__model: &$first| __model $(. $rest)+ .clone(),
116 )
117 };
118}