ash_jsonapi/attribute.rs
1//! Attribute types: one Rust type, its JSON Schema, and how it is read back.
2//!
3//! [`resource!`](crate::resource!) needs three things for every field it is
4//! given: the JSON Schema that describes it, how to read it out of a
5//! validated document, and how to write it back into a response. Rather than
6//! matching on type names in the macro — which would only ever know the types
7//! the macro was written for — each is a method on this trait.
8//!
9//! Implementations ship for [`String`], the integer and float types, [`bool`],
10//! and [`Option<T>`] over any of them. Implement it yourself for a newtype, an
11//! enum, or anything else you want a resource to carry:
12//!
13//! ```ignore
14//! struct Priority(u8);
15//!
16//! impl Attribute for Priority {
17//! fn schema() -> serde_json::Value {
18//! serde_json::json!({ "type": "integer", "minimum": 1, "maximum": 5 })
19//! }
20//!
21//! fn read(value: &serde_json::Value) -> Option<Self> {
22//! value.as_u64().map(|n| Priority(n as u8))
23//! }
24//!
25//! fn write(&self) -> serde_json::Value {
26//! serde_json::Value::from(self.0)
27//! }
28//! }
29//! ```
30//!
31//! Validation still happens against the schema before `read` runs, so `read`
32//! is reached only for a value the schema already accepted.
33
34/// A type a resource attribute can hold.
35pub trait Attribute: Sized {
36 /// The JSON Schema for this type, as it appears under `attributes`.
37 fn schema() -> serde_json::Value;
38
39 /// Read the value out of a validated document.
40 ///
41 /// `None` means the value was not of this type. The schema has already
42 /// rejected anything ill-typed, so this fires only for a type whose
43 /// schema is looser than its `read` — report it rather than defaulting.
44 fn read(value: &serde_json::Value) -> Option<Self>;
45
46 /// Write the value into a response's `attributes`.
47 fn write(&self) -> serde_json::Value;
48
49 /// Whether the member may be absent.
50 ///
51 /// Only [`Option`] overrides this. It drives the `required` list of the
52 /// generated schema, so an optional field is one that may be omitted.
53 fn required() -> bool {
54 true
55 }
56}
57
58/// A string attribute in a declared JSON Schema `format`.
59///
60/// The wrapper that puts `format` to work: a resource field typed
61/// `Formatted<Email>` generates `{"type": "string", "format": "email"}`, and
62/// the validator asserts it — so a malformed address is a `422` with a
63/// pointer at the member, checked before any of your code runs.
64///
65/// ```text
66/// ash_jsonapi::resource! {
67/// User as "user" at "/users",
68/// …
69/// attributes: {
70/// email: Formatted<Email>,
71/// joined: Formatted<Date>,
72/// },
73/// }
74/// ```
75///
76/// The inner value is a [`String`]; the type parameter only carries which
77/// format to declare. For a format the specification does not define, give
78/// the validator a check with
79/// [`ValidatorBuilder::format`](crate::validation::ValidatorBuilder::format)
80/// and write your own [`FormatName`].
81// The derives are written out rather than `#[derive]`d: a derive would bound
82// each impl on `F`, and `F` is a marker that never exists at runtime. A user's
83// format type should not have to be `Clone` for their resource to be.
84pub struct Formatted<F: FormatName> {
85 value: String,
86 format: std::marker::PhantomData<F>,
87}
88
89impl<F: FormatName> Clone for Formatted<F> {
90 fn clone(&self) -> Self {
91 Self {
92 value: self.value.clone(),
93 format: std::marker::PhantomData,
94 }
95 }
96}
97
98impl<F: FormatName> std::fmt::Debug for Formatted<F> {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 // Shown as the format it declares, so a log line says what failed.
101 write!(f, "Formatted<{}>({:?})", F::NAME, self.value)
102 }
103}
104
105impl<F: FormatName> Default for Formatted<F> {
106 fn default() -> Self {
107 Self {
108 value: String::new(),
109 format: std::marker::PhantomData,
110 }
111 }
112}
113
114impl<F: FormatName> PartialEq for Formatted<F> {
115 fn eq(&self, other: &Self) -> bool {
116 self.value == other.value
117 }
118}
119
120impl<F: FormatName> Eq for Formatted<F> {}
121
122impl<F: FormatName> PartialOrd for Formatted<F> {
123 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
124 Some(self.cmp(other))
125 }
126}
127
128impl<F: FormatName> Ord for Formatted<F> {
129 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
130 self.value.cmp(&other.value)
131 }
132}
133
134impl<F: FormatName> std::hash::Hash for Formatted<F> {
135 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
136 self.value.hash(state);
137 }
138}
139
140impl<F: FormatName> Formatted<F> {
141 /// The string itself.
142 pub fn as_str(&self) -> &str {
143 &self.value
144 }
145
146 /// Take the string out.
147 pub fn into_inner(self) -> String {
148 self.value
149 }
150}
151
152impl<F: FormatName> std::fmt::Display for Formatted<F> {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.write_str(&self.value)
155 }
156}
157
158impl<F: FormatName> Attribute for Formatted<F> {
159 fn schema() -> serde_json::Value {
160 serde_json::json!({ "type": "string", "format": F::NAME })
161 }
162
163 fn read(value: &serde_json::Value) -> Option<Self> {
164 // The format itself is the validator's to check, and it already has
165 // by the time this runs.
166 value.as_str().map(|value| Self {
167 value: value.to_string(),
168 format: std::marker::PhantomData,
169 })
170 }
171
172 fn write(&self) -> serde_json::Value {
173 serde_json::Value::from(self.value.clone())
174 }
175}
176
177/// The name of a JSON Schema `format`, as it appears in a schema.
178///
179/// Implement it on a marker type to declare a format this crate does not
180/// ship — pairing it with
181/// [`ValidatorBuilder::format`](crate::validation::ValidatorBuilder::format),
182/// which supplies the check:
183///
184/// ```ignore
185/// struct EmployeeId;
186/// impl FormatName for EmployeeId { const NAME: &'static str = "employee-id"; }
187/// ```
188pub trait FormatName {
189 /// The `format` keyword's value, e.g. `"email"`.
190 const NAME: &'static str;
191}
192
193/// The formats ash-jsonschema asserts, as marker types for [`Formatted`].
194///
195/// Only these are checked without supplying your own function; any other name
196/// is an annotation until you give it one.
197macro_rules! formats {
198 ($($(#[$doc:meta])* $name:ident => $format:literal),+ $(,)?) => {
199 $(
200 $(#[$doc])*
201 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
202 pub struct $name;
203
204 impl FormatName for $name {
205 const NAME: &'static str = $format;
206 }
207 )+
208 };
209}
210
211formats! {
212 /// RFC 3339 timestamp, e.g. `2024-02-29T12:00:00Z`.
213 DateTime => "date-time",
214 /// RFC 3339 full-date, e.g. `2024-02-29`.
215 Date => "date",
216 /// RFC 3339 full-time.
217 Time => "time",
218 /// ISO 8601 duration, e.g. `P3DT4H`.
219 Duration => "duration",
220 /// RFC 5321 mailbox.
221 Email => "email",
222 /// RFC 6531 internationalized mailbox.
223 IdnEmail => "idn-email",
224 /// RFC 1123 host name.
225 Hostname => "hostname",
226 /// Dotted-quad address.
227 Ipv4 => "ipv4",
228 /// RFC 4291 address.
229 Ipv6 => "ipv6",
230 /// RFC 4122 UUID.
231 Uuid => "uuid",
232 /// RFC 6901 JSON Pointer.
233 JsonPointer => "json-pointer",
234 /// Relative JSON Pointer.
235 RelativeJsonPointer => "relative-json-pointer",
236}
237
238/// `String` → `{"type": "string"}`.
239impl Attribute for String {
240 fn schema() -> serde_json::Value {
241 serde_json::json!({ "type": "string" })
242 }
243
244 fn read(value: &serde_json::Value) -> Option<Self> {
245 value.as_str().map(ToString::to_string)
246 }
247
248 fn write(&self) -> serde_json::Value {
249 serde_json::Value::from(self.clone())
250 }
251}
252
253/// `bool` → `{"type": "boolean"}`.
254impl Attribute for bool {
255 fn schema() -> serde_json::Value {
256 serde_json::json!({ "type": "boolean" })
257 }
258
259 fn read(value: &serde_json::Value) -> Option<Self> {
260 value.as_bool()
261 }
262
263 fn write(&self) -> serde_json::Value {
264 serde_json::Value::from(*self)
265 }
266}
267
268/// The integer types, each with the bounds its width actually has.
269///
270/// A `u8` field rejects `300` at validation rather than wrapping or failing
271/// later, because the schema carries the real range.
272macro_rules! integer_attribute {
273 ($($ty:ty => $as:ident),+ $(,)?) => {
274 $(
275 impl Attribute for $ty {
276 fn schema() -> serde_json::Value {
277 serde_json::json!({
278 "type": "integer",
279 "minimum": <$ty>::MIN,
280 "maximum": <$ty>::MAX,
281 })
282 }
283
284 fn read(value: &serde_json::Value) -> Option<Self> {
285 value.$as().and_then(|n| <$ty>::try_from(n).ok())
286 }
287
288 fn write(&self) -> serde_json::Value {
289 serde_json::Value::from(*self)
290 }
291 }
292 )+
293 };
294}
295
296integer_attribute! {
297 i8 => as_i64, i16 => as_i64, i32 => as_i64, i64 => as_i64,
298 u8 => as_u64, u16 => as_u64, u32 => as_u64, u64 => as_u64,
299}
300
301/// The float types → `{"type": "number"}`.
302macro_rules! float_attribute {
303 ($($ty:ty),+ $(,)?) => {
304 $(
305 impl Attribute for $ty {
306 fn schema() -> serde_json::Value {
307 serde_json::json!({ "type": "number" })
308 }
309
310 fn read(value: &serde_json::Value) -> Option<Self> {
311 value.as_f64().map(|n| n as $ty)
312 }
313
314 fn write(&self) -> serde_json::Value {
315 serde_json::Value::from(*self)
316 }
317 }
318 )+
319 };
320}
321
322float_attribute!(f32, f64);
323
324/// `Option<T>` — the member may be absent, and `null` reads as `None`.
325impl<T: Attribute> Attribute for Option<T> {
326 fn schema() -> serde_json::Value {
327 T::schema()
328 }
329
330 fn read(value: &serde_json::Value) -> Option<Self> {
331 // Absent and explicit null are the same thing here: no value.
332 if value.is_null() {
333 return Some(None);
334 }
335 T::read(value).map(Some)
336 }
337
338 fn write(&self) -> serde_json::Value {
339 match self {
340 Some(value) => value.write(),
341 None => serde_json::Value::Null,
342 }
343 }
344
345 fn required() -> bool {
346 false
347 }
348}