Skip to main content

ash_jsonapi/
declare.rs

1//! Declaring a resource once.
2//!
3//! Without this, the same field list is written four times: the
4//! [`Schema`](crate::Schema), the [`Resource`](crate::crud::Resource) impl
5//! that serializes it, the [`FromRequest`](crate::extract::FromRequest) impl
6//! that reads a body back, and the JSON Schema those attributes must satisfy.
7//! Four copies that have to agree, with nothing checking that they do —
8//! rename a field and the compiler stays happy while requests fail at
9//! runtime.
10//!
11//! [`resource!`](crate::resource!) takes the list once and writes all four.
12
13use crate::context::Context;
14use crate::error::JsonApiError;
15
16/// Read one attribute out of a validated document.
17///
18/// Used by [`resource!`](crate::resource!). The schema has already checked
19/// the member's type, so a failure here means the two disagree — a
20/// hand-written [`Attribute`](crate::attribute::Attribute) whose `schema` is
21/// looser than its `read` — and it is reported as a `422` pointing at the
22/// member rather than quietly defaulted.
23pub fn read_attribute<T: crate::attribute::Attribute>(
24    document: &serde_json::Value,
25    name: &str,
26    ctx: &Context,
27) -> Result<T, JsonApiError> {
28    let value = document
29        .pointer(&format!("/data/attributes/{name}"))
30        .unwrap_or(&serde_json::Value::Null);
31
32    T::read(value).ok_or_else(|| {
33        JsonApiError::invalid(
34            ctx,
35            format!("`{name}` is not of the expected type"),
36            format!("/data/attributes/{name}"),
37        )
38    })
39}
40
41/// Read one relationship's id out of a validated document.
42///
43/// Absent linkage is `None`, so a create that omits an optional relationship
44/// is not an error here — whether it is required is the schema's business.
45pub fn read_relationship(document: &serde_json::Value, name: &str) -> Option<String> {
46    document
47        .pointer(&format!("/data/relationships/{name}/data/id"))
48        .and_then(|id| id.as_str())
49        .map(ToString::to_string)
50}
51
52/// Read a to-many relationship's ids out of a validated document.
53pub fn read_relationships(document: &serde_json::Value, name: &str) -> Vec<String> {
54    document
55        .pointer(&format!("/data/relationships/{name}/data"))
56        .and_then(|data| data.as_array())
57        .map(|ids| {
58            ids.iter()
59                .filter_map(|id| id.get("id").and_then(|id| id.as_str()))
60                .map(ToString::to_string)
61                .collect()
62        })
63        .unwrap_or_default()
64}
65
66/// Declare a resource once: its schema, its serialization, and its parsing.
67///
68/// ```ignore
69/// ash_jsonapi::resource! {
70///     Todo as "todo" at "/todos",
71///     state: App,
72///     schema: TodoSchema,
73///     input: NewTodo,
74///     id: id,
75///     attributes: { message: String, done: bool },
76/// }
77/// ```
78///
79/// That one declaration expands to everything you would otherwise write by
80/// hand:
81///
82/// - `struct TodoSchema` and its [`Schema`](crate::Schema) impl — the name,
83///   the base path, and the relationships.
84/// - `struct NewTodo`, the parsed body, with a public field per attribute,
85///   plus its [`FromRequest`](crate::extract::FromRequest) impl: validate
86///   against the resource's registered validator, then read each field.
87/// - `impl Resource<App> for Todo` — `NAME`, `PATH`, and a `to_resource`
88///   writing every attribute and relationship.
89/// - `Todo::attributes_schema()`, the JSON Schema for the attributes, built
90///   from each field's [`Attribute`](crate::attribute::Attribute) impl.
91///
92/// The field list appears once, so those four cannot drift apart. Field types
93/// need [`Attribute`](crate::attribute::Attribute) — implemented already for
94/// the standard scalars, `Option<T>` over them, and anything you implement it
95/// on yourself.
96///
97/// The `schema:` and `input:` names are yours to pick. A `macro_rules!` macro
98/// cannot build one identifier from another, so defaulting them to
99/// `TodoSchema`/`NewTodo` would mean either a `paste`-style dependency in
100/// every user's tree or a companion proc-macro crate — more than two lines of
101/// ceremony is worth. They are also the names *you* write when you reference
102/// the generated types, so naming them here keeps that explicit.
103/// `TodoSchema` and `NewTodo` are the conventional shapes.
104///
105/// # Relationships
106///
107/// ```ignore
108/// ash_jsonapi::resource! {
109///     Todo as "todo" at "/todos",
110///     state: App,
111///     schema: TodoSchema,
112///     input: NewTodo,
113///     id: id,
114///     attributes: { message: String },
115///     relationships: { owner -> one "user", tags -> many "tag" },
116/// }
117/// ```
118///
119/// Target type and arity are declared once and reach the linkage, both link
120/// URLs, and the request schema. `-> one` reads a field holding one id;
121/// `-> many` a field holding a collection of them. On the input struct a
122/// to-one becomes `Option<String>` — absent linkage is not an error — and a
123/// to-many becomes `Vec<String>`.
124///
125/// # What it does not write
126///
127/// The storage impls, and the validator's registration. Where rows live is
128/// yours: this writes the wire format, not your data layer. Pair it with
129/// [`api!`](crate::api!) for the routes.
130///
131/// Need something it does not express — a computed attribute, an attribute
132/// whose name differs from its field, a body that is not JSON:API at all?
133/// Write the impls by hand. They are three ordinary traits, and this is
134/// shorthand for the common shape rather than the only way in.
135#[macro_export]
136macro_rules! resource {
137    (
138        $resource:ident as $name:literal at $base:literal,
139        state: $state:ident,
140        schema: $schema:ident,
141        input: $input:ident,
142        id: $id:ident,
143        attributes: { $($field:ident : $ty:ty),* $(,)? }
144        $(, relationships: { $($rel:ident -> $arity:ident $target:literal),* $(,)? })?
145        $(,)?
146    ) => {
147        #[doc = ::std::concat!("The JSON:API schema for [`", ::std::stringify!($resource), "`].")]
148        #[derive(Debug, Clone, Copy, Default)]
149        pub struct $schema;
150
151        impl $crate::serialize::Schema for $schema {
152            type Relationship = $crate::serialize::Rel;
153
154            fn name(&self) -> &str {
155                $name
156            }
157
158            fn base_path(&self) -> &str {
159                $base
160            }
161
162            fn relationships(&self) -> &[$crate::serialize::Rel] {
163                // A `const` rather than an inline array: the slice outlives
164                // the call, and `Rel`'s constructors are `const` for exactly
165                // this.
166                const RELATIONSHIPS: &[$crate::serialize::Rel] =
167                    &[$($($crate::__rel_def!($rel, $arity, $target)),*)?];
168                RELATIONSHIPS
169            }
170        }
171
172        #[doc = ::std::concat!("A validated request body for [`", ::std::stringify!($resource), "`].")]
173        #[derive(Debug, Clone)]
174        pub struct $input {
175            $(
176                #[doc = ::std::concat!("The `", ::std::stringify!($field), "` attribute.")]
177                pub $field: $ty,
178            )*
179            $($(
180                #[doc = ::std::concat!("Linkage for the `", ::std::stringify!($rel), "` relationship.")]
181                pub $rel: $crate::__rel_input_ty!($arity),
182            )*)?
183        }
184
185        impl $crate::extract::FromRequest<$state> for $input {
186            async fn from_request(
187                request: ::axum::extract::Request,
188                state: &$state,
189                ctx: &$crate::context::Context,
190            ) -> ::std::result::Result<Self, $crate::response::Errors> {
191                let validator = $crate::crud::validator(state, $name, ctx)?;
192                let document = $crate::extract::validated(request, ctx, validator).await?;
193
194                // Every attribute is read before any failure is returned, so
195                // a body with two bad members reports both — the same reason
196                // validation runs in `Mode::All`.
197                #[allow(unused_mut)]
198                let mut failures: ::std::vec::Vec<$crate::error::JsonApiError> =
199                    ::std::vec::Vec::new();
200
201                $(
202                    let $field = match $crate::declare::read_attribute::<$ty>(
203                        &document,
204                        ::std::stringify!($field),
205                        ctx,
206                    ) {
207                        ::std::result::Result::Ok(value) => ::std::option::Option::Some(value),
208                        ::std::result::Result::Err(err) => {
209                            failures.push(err);
210                            ::std::option::Option::None
211                        }
212                    };
213                )*
214
215                if !failures.is_empty() {
216                    return ::std::result::Result::Err($crate::response::Errors(failures));
217                }
218
219                ::std::result::Result::Ok(Self {
220                    $(
221                        // Unreachable while `failures` is empty: the read
222                        // either produced a value or pushed a failure.
223                        $field: $field.expect("read succeeded"),
224                    )*
225                    $($(
226                        $rel: $crate::__rel_read!(document, $rel, $arity),
227                    )*)?
228                })
229            }
230        }
231
232        impl $resource {
233            /// The JSON Schema this resource's `attributes` must satisfy.
234            ///
235            /// Built from each field's `Attribute` impl. Hand it to
236            /// `DocumentValidator::builder(…).attributes(…)`.
237            pub fn attributes_schema() -> $crate::__serde_json::Value {
238                #[allow(unused_mut)]
239                let mut properties = $crate::__serde_json::Map::new();
240                #[allow(unused_mut)]
241                let mut required: ::std::vec::Vec<$crate::__serde_json::Value> = ::std::vec::Vec::new();
242
243                $(
244                    properties.insert(
245                        ::std::string::String::from(::std::stringify!($field)),
246                        <$ty as $crate::attribute::Attribute>::schema(),
247                    );
248                    if <$ty as $crate::attribute::Attribute>::required() {
249                        required.push($crate::__serde_json::Value::from(::std::stringify!($field)));
250                    }
251                )*
252
253                $crate::__serde_json::json!({
254                    "type": "object",
255                    "properties": $crate::__serde_json::Value::Object(properties),
256                    "required": $crate::__serde_json::Value::Array(required),
257                })
258            }
259
260            /// A validator for this resource's request bodies.
261            ///
262            /// The whole of what registering a resource takes: build it at
263            /// startup, hand it back from [`Validators::validator`](crate::crud::Validators::validator).
264            pub fn validator() -> ::std::result::Result<
265                $crate::validation::DocumentValidator,
266                $crate::validation::BuildError,
267            > {
268                $crate::validation::DocumentValidator::builder(&$schema)
269                    .attributes(Self::attributes_schema())
270                    .build()
271            }
272        }
273
274        impl $crate::crud::Resource<$state> for $resource {
275            type Create = $input;
276            type Update = $input;
277
278            const NAME: &'static str = $name;
279            const PATH: &'static str = $base;
280
281            fn to_resource(
282                &self,
283                _state: &$state,
284                _ctx: &$crate::context::Context,
285            ) -> ::std::result::Result<$crate::document::ResourceObject, $crate::error::JsonApiError>
286            {
287                #[allow(unused_mut)]
288                // `record_owned`, not `record`: the id is rendered here and
289                // handed over, rather than rendered, lent, and rendered again.
290                let mut record = $crate::serialize::Serializer::new(&$schema)
291                    .record_owned(::std::string::ToString::to_string(&self.$id));
292
293                $(
294                    record = record.attr(
295                        ::std::stringify!($field),
296                        <$ty as $crate::attribute::Attribute>::write(&self.$field),
297                    );
298                )*
299
300                $($(
301                    record = $crate::__rel_write!(record, self, $rel, $arity);
302                )*)?
303
304                ::std::result::Result::Ok(record.build())
305            }
306        }
307    };
308}
309
310/// One relationship's `Rel`, by arity.
311#[doc(hidden)]
312#[macro_export]
313macro_rules! __rel_def {
314    ($rel:ident, one, $target:literal) => {
315        $crate::serialize::Rel::to_one(::std::stringify!($rel), $target)
316    };
317    ($rel:ident, many, $target:literal) => {
318        $crate::serialize::Rel::to_many(::std::stringify!($rel), $target)
319    };
320    ($rel:ident, $other:ident, $target:literal) => {
321        ::std::compile_error!(::std::concat!(
322            "unknown relationship arity `",
323            ::std::stringify!($other),
324            "`; expected `one` or `many`"
325        ))
326    };
327}
328
329/// The input struct's field type for one relationship.
330#[doc(hidden)]
331#[macro_export]
332macro_rules! __rel_input_ty {
333    (one) => { ::std::option::Option<::std::string::String> };
334    (many) => { ::std::vec::Vec<::std::string::String> };
335    ($other:ident) => {
336        ::std::compile_error!(::std::concat!(
337            "unknown relationship arity `",
338            ::std::stringify!($other),
339            "`; expected `one` or `many`"
340        ))
341    };
342}
343
344/// Reading one relationship out of a validated document, by arity.
345#[doc(hidden)]
346#[macro_export]
347macro_rules! __rel_read {
348    ($document:ident, $rel:ident, one) => {
349        $crate::declare::read_relationship(&$document, ::std::stringify!($rel))
350    };
351    ($document:ident, $rel:ident, many) => {
352        $crate::declare::read_relationships(&$document, ::std::stringify!($rel))
353    };
354}
355
356/// Writing one relationship's linkage, by arity.
357#[doc(hidden)]
358#[macro_export]
359macro_rules! __rel_write {
360    ($record:ident, $self:ident, $rel:ident, one) => {
361        $record.rel(
362            ::std::stringify!($rel),
363            ::std::string::ToString::to_string(&$self.$rel),
364        )
365    };
366    ($record:ident, $self:ident, $rel:ident, many) => {
367        $record.rel_many(
368            ::std::stringify!($rel),
369            $self.$rel.iter().map(::std::string::ToString::to_string),
370        )
371    };
372}
373
374/// Implement [`Validators`](crate::crud::Validators) from a list of resources.
375///
376/// The validators have to live somewhere on your state, and looking them up
377/// by name is the same match every time:
378///
379/// ```ignore
380/// ash_jsonapi::registry! {
381///     App { todos: Todo, users: User }
382/// }
383/// ```
384///
385/// `todos` and `users` are fields on your state holding a
386/// [`DocumentValidator`](crate::validation::DocumentValidator) — or anything
387/// that derefs to one, which is usually what you want, since your state has
388/// to be [`Clone`] and a validator is not. The names they answer to are the
389/// resources' own `NAME`. Build the fields with the generated
390/// `Todo::validator()` at startup:
391///
392/// ```ignore
393/// let state = App {
394///     todos: Arc::new(Todo::validator()?),
395///     users: Arc::new(User::validator()?),
396///     /* … the rest of your state … */
397/// };
398/// ```
399///
400/// # With hooks
401///
402/// A state that carries hooks as well as validators names the field after
403/// the resource list:
404///
405/// ```ignore
406/// ash_jsonapi::registry! {
407///     App { todos: Todo, users: User }
408///     hooks: hooks
409/// }
410/// ```
411///
412/// Without this arm the macro writes the whole
413/// [`Validators`](crate::crud::Validators) impl, leaving nowhere to add
414/// [`hooks`](crate::crud::Validators::hooks) — so a service wanting both had
415/// to hand-write the lookup.
416///
417/// A resource whose bodies you never parse — a read-only one — needs no
418/// entry. A service where *nothing* parses a body needs no `registry!` at
419/// all: [`Validators::validator`](crate::crud::Validators::validator) defaults to
420/// `None`, so `impl Validators for App {}` is the whole wiring.
421///
422/// Omitting an entry for a resource you *do* route `CREATE` or `UPDATE` for
423/// is a wiring bug, and reported as one — the request fails naming the
424/// resource, rather than skipping validation.
425#[macro_export]
426macro_rules! registry {
427    // With a hooks field: the state carries both, which is the shape a
428    // service with validators *and* an audit trail needs. Spelled as a
429    // separate arm rather than an optional trailing field so the common case
430    // stays a one-liner.
431    ($state:ident { $($field:ident : $resource:ty),* $(,)? } hooks: $hooks:ident $(,)?) => {
432        $crate::__registry_impl!($state { $($field : $resource),* } hooks: $hooks);
433    };
434
435    ($state:ident { $($field:ident : $resource:ty),* $(,)? }) => {
436        $crate::__registry_impl!($state { $($field : $resource),* });
437    };
438}
439
440/// The `Validators` impl both [`registry!`](crate::registry!) arms write.
441#[doc(hidden)]
442#[macro_export]
443macro_rules! __registry_impl {
444    ($state:ident { $($field:ident : $resource:ty),* } $(hooks: $hooks:ident)?) => {
445        impl $crate::crud::Validators for $state {
446            $(
447                fn hooks(&self) -> ::std::option::Option<&$crate::hook::Hooks> {
448                    ::std::option::Option::Some(&self.$hooks)
449                }
450            )?
451
452            fn validator(
453                &self,
454                resource: &str,
455            ) -> ::std::option::Option<&$crate::validation::DocumentValidator> {
456                match resource {
457                    $(
458                        <$resource as $crate::crud::Resource<$state>>::NAME => {
459                            // `&*` so the field may be a validator, an
460                            // `Arc<DocumentValidator>`, or anything else that
461                            // derefs to one — state must be `Clone`, and a
462                            // bare validator is not.
463                            ::std::option::Option::Some(&*self.$field)
464                        }
465                    )*
466                    _ => ::std::option::Option::None,
467                }
468            }
469        }
470    };
471}