ash_jsonapi/serialize.rs
1//! Your data + your schema → [`ResourceObject`].
2//!
3//! Describe a resource once by implementing [`Schema`] and
4//! [`RelationshipDef`], and this module writes the JSON:API envelope for it:
5//! the `type`/`id` wrapper, relationship linkage, and `self`/`related` links.
6//! Nothing here needs a particular ORM or data layer — a `Schema` is three
7//! methods over whatever types you already have.
8//!
9//! ```ignore
10//! struct Todo;
11//!
12//! impl Schema for Todo {
13//! type Relationship = Rel;
14//!
15//! fn name(&self) -> &str { "todo" }
16//! fn base_path(&self) -> &str { "/todos" }
17//! fn relationships(&self) -> &[Rel] { &[Rel::to_one("owner", "user")] }
18//! }
19//!
20//! let object = Serializer::new(&Todo)
21//! .record("t_1")
22//! .attr("message", "buy milk")
23//! .rel("owner", "u_1")
24//! .build();
25//! ```
26//!
27//! The point is that you state a relationship's target type and arity *once*,
28//! in the schema. The linkage shape and both link URLs follow from it, so no
29//! call site spells them and none can drift.
30//!
31//! Using `ash-domain`? Its `ResourceSchema` implements these traits already —
32//! see [`crate::domain`], and skip writing them yourself.
33
34use std::collections::BTreeMap;
35
36use crate::document::{Linkage, Links, Relationship, ResourceIdentifier, ResourceObject};
37
38/// One relationship your resource declares.
39///
40/// Only the arity matters to JSON:API: a to-one relationship serializes as a
41/// single linkage object, a to-many as an array. Whatever distinction your
42/// data layer draws beyond that — belongs-to versus has-one, join tables — is
43/// its business, not the wire format's.
44///
45/// [`Rel`] is a ready-made implementation; write your own only if you already
46/// have a relationship type to borrow.
47pub trait RelationshipDef {
48 /// The member name — `owner`, `comments`.
49 fn name(&self) -> &str;
50
51 /// The JSON:API `type` on the far side: the related resource's name.
52 fn target(&self) -> &str;
53
54 /// Whether the far side holds many resources.
55 fn is_to_many(&self) -> bool;
56}
57
58/// A relationship, ready to use.
59///
60/// Saves declaring a type just to satisfy [`Schema::Relationship`]:
61///
62/// ```ignore
63/// fn relationships(&self) -> &[Rel] {
64/// &[Rel::to_one("owner", "user"), Rel::to_many("tags", "tag")]
65/// }
66/// ```
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct Rel {
69 name: &'static str,
70 target: &'static str,
71 to_many: bool,
72}
73
74impl Rel {
75 /// A relationship with one resource on the far side.
76 pub const fn to_one(name: &'static str, target: &'static str) -> Self {
77 Self {
78 name,
79 target,
80 to_many: false,
81 }
82 }
83
84 /// A relationship with many resources on the far side.
85 pub const fn to_many(name: &'static str, target: &'static str) -> Self {
86 Self {
87 name,
88 target,
89 to_many: true,
90 }
91 }
92}
93
94impl RelationshipDef for Rel {
95 fn name(&self) -> &str {
96 self.name
97 }
98
99 fn target(&self) -> &str {
100 self.target
101 }
102
103 fn is_to_many(&self) -> bool {
104 self.to_many
105 }
106}
107
108/// A resource with no relationships.
109///
110/// The `Schema::Relationship` to use when there are none — so a flat resource
111/// needs no relationship type of its own:
112///
113/// ```ignore
114/// impl Schema for Note {
115/// type Relationship = NoRelationships;
116///
117/// fn name(&self) -> &str { "note" }
118/// fn base_path(&self) -> &str { "/notes" }
119/// fn relationships(&self) -> &[NoRelationships] { &[] }
120/// }
121/// ```
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum NoRelationships {}
124
125impl RelationshipDef for NoRelationships {
126 fn name(&self) -> &str {
127 match *self {}
128 }
129
130 fn target(&self) -> &str {
131 match *self {}
132 }
133
134 fn is_to_many(&self) -> bool {
135 match *self {}
136 }
137}
138
139/// What serialization needs to know about one resource.
140///
141/// Three methods. Implement it on whatever already describes your resource —
142/// a marker struct, a config value, or a schema type you own.
143pub trait Schema {
144 type Relationship: RelationshipDef;
145
146 /// `ResourceSchema::name` → the JSON:API `type`.
147 fn name(&self) -> &str;
148
149 /// Every declared relationship.
150 fn relationships(&self) -> &[Self::Relationship];
151
152 /// Where the resource is mounted, e.g. `/api/v1/todos`.
153 ///
154 /// Used to build `self` and `related` links, so it should match the path
155 /// the router actually serves.
156 fn base_path(&self) -> &str;
157}
158
159/// Serializes one resource's records into JSON:API resource objects.
160///
161/// Borrows the schema rather than copying it, so your declaration stays the
162/// single source of truth.
163#[derive(Debug, Clone, Copy)]
164pub struct Serializer<'a, S: Schema> {
165 schema: &'a S,
166}
167
168impl<'a, S: Schema> Serializer<'a, S> {
169 pub fn new(schema: &'a S) -> Self {
170 Self { schema }
171 }
172
173 /// The `self` link for one resource.
174 pub fn self_link(&self, id: &str) -> String {
175 format!("{}/{}", self.schema.base_path().trim_end_matches('/'), id)
176 }
177
178 /// Start building a resource object for `id`.
179 ///
180 /// The usual entry point. Attributes and relationships are added
181 /// fluently, and the type, the `self` link and every relationship link
182 /// come from the schema:
183 ///
184 /// ```text
185 /// serializer
186 /// .record(&id)
187 /// .attr("message", "buy milk")
188 /// .rel("owner", "u_01H8X")
189 /// .build()
190 /// ```ignore
191 pub fn record(&self, id: &str) -> Record<'a, S> {
192 self.record_owned(id.to_string())
193 }
194
195 /// [`record`](Self::record), taking an id you already own.
196 ///
197 /// The same builder, without copying the id. A caller that has just
198 /// rendered its primary key — which [`resource!`](crate::resource!) does
199 /// on every row — would otherwise allocate it, lend it here, and have it
200 /// allocated again immediately.
201 pub fn record_owned(&self, id: String) -> Record<'a, S> {
202 Record {
203 schema: self.schema,
204 id,
205 attributes: BTreeMap::new(),
206 related: BTreeMap::new(),
207 }
208 }
209
210 /// Serialize a record from prepared maps.
211 ///
212 /// `attributes` is the record's data, already projected for any sparse
213 /// fieldset. `related` maps a relationship name to the ids on its far
214 /// side. Prefer [`Serializer::record`] unless the maps already exist —
215 /// this is the bulk path, for a listing built from a data layer.
216 pub fn serialize(
217 &self,
218 id: &str,
219 attributes: BTreeMap<String, serde_json::Value>,
220 related: &BTreeMap<String, Vec<String>>,
221 ) -> ResourceObject {
222 // The row's `self` link is the prefix every one of its relationship
223 // links is built from, so it is computed once here and borrowed by
224 // each. Rebuilding it per relationship was the single most expensive
225 // thing a listing did: a row with three relationships formatted the
226 // same `{base}/{id}` four times, and a hundred-row page did it four
227 // hundred.
228 let self_link = self.self_link(id);
229
230 let mut object = ResourceObject::new(self.schema.name(), id);
231 object.attributes = attributes;
232
233 // Borrowed while the relationships are built, then moved onto the
234 // object — so a flat resource, which has no relationships to share
235 // the prefix with, never copies it.
236 for (name, ids) in related {
237 if let Some(rel) = self.relationship_at(&self_link, name, ids) {
238 object = object.relationship(name.clone(), rel);
239 }
240 }
241
242 object.with_links(Links::this(self_link))
243 }
244
245 /// Build one relationship's linkage and links from the schema.
246 ///
247 /// Returns `None` for a name the schema does not declare.
248 pub fn relationship(&self, id: &str, name: &str, ids: &[String]) -> Option<Relationship> {
249 self.relationship_at(&self.self_link(id), name, ids)
250 }
251
252 /// [`relationship`](Self::relationship), against an already-built `self`
253 /// link.
254 ///
255 /// Split out so a row that carries several relationships formats its own
256 /// link once rather than once per relationship — see [`Self::serialize`].
257 fn relationship_at(&self, self_link: &str, name: &str, ids: &[String]) -> Option<Relationship> {
258 self.relationship_owned(self_link, name, ids.to_vec())
259 }
260
261 /// [`relationship_at`](Self::relationship_at), taking ids it may consume.
262 ///
263 /// The builder owns its linkage ids and drops them straight after, so
264 /// moving them onto the identifiers saves a copy of every id on every
265 /// relationship of every row.
266 fn relationship_owned(
267 &self,
268 self_link: &str,
269 name: &str,
270 ids: Vec<String>,
271 ) -> Option<Relationship> {
272 let def = self
273 .schema
274 .relationships()
275 .iter()
276 .find(|r| r.name() == name)?;
277
278 let identifiers: Vec<_> = ids
279 .into_iter()
280 .map(|target_id| ResourceIdentifier::new(def.target(), target_id))
281 .collect();
282
283 // Arity is the schema's, not the data's: a to-one relationship with no
284 // target is an explicit null, never an empty array.
285 let data = if def.is_to_many() {
286 Linkage::Many(identifiers)
287 } else {
288 Linkage::One(identifiers.into_iter().next())
289 };
290
291 // Both links extend the same prefix, so each is one allocation sized
292 // up front rather than a `format!` that measures and grows.
293 let mut this =
294 String::with_capacity(self_link.len() + "/relationships/".len() + name.len());
295 this.push_str(self_link);
296 this.push_str("/relationships/");
297 this.push_str(name);
298
299 let mut related = String::with_capacity(self_link.len() + 1 + name.len());
300 related.push_str(self_link);
301 related.push('/');
302 related.push_str(name);
303
304 Some(Relationship {
305 data: Some(data),
306 links: Some(Links::this(this).related(related)),
307 })
308 }
309}
310
311/// A resource object under construction. Created by [`Serializer::record`].
312#[must_use = "a record does nothing until `build` is called"]
313pub struct Record<'a, S: Schema> {
314 schema: &'a S,
315 id: String,
316 attributes: BTreeMap<String, serde_json::Value>,
317 related: BTreeMap<String, Vec<String>>,
318}
319
320impl<S: Schema> Record<'_, S> {
321 /// Set one attribute.
322 pub fn attr(mut self, name: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
323 self.attributes.insert(name.into(), value.into());
324 self
325 }
326
327 /// Set every attribute at once, from a record's own data.
328 pub fn attrs(
329 mut self,
330 attributes: impl IntoIterator<Item = (String, serde_json::Value)>,
331 ) -> Self {
332 self.attributes.extend(attributes);
333 self
334 }
335
336 /// Link a to-one relationship. The target type comes from the schema.
337 pub fn rel(self, name: impl Into<String>, id: impl Into<String>) -> Self {
338 self.rel_many(name, [id.into()])
339 }
340
341 /// Link a to-many relationship.
342 pub fn rel_many(
343 mut self,
344 name: impl Into<String>,
345 ids: impl IntoIterator<Item = String>,
346 ) -> Self {
347 self.related.insert(name.into(), ids.into_iter().collect());
348 self
349 }
350
351 /// Finish the resource object.
352 ///
353 /// Consumes the builder's own maps rather than handing
354 /// [`serialize`](Serializer::serialize) a reference to them: the linkage
355 /// ids are moved onto the resource object instead of being cloned out of
356 /// a map that is about to be dropped.
357 pub fn build(self) -> ResourceObject {
358 let serializer = Serializer::new(self.schema);
359 let self_link = serializer.self_link(&self.id);
360
361 let mut object = ResourceObject::new(self.schema.name(), self.id);
362 object.attributes = self.attributes;
363
364 for (name, ids) in self.related {
365 if let Some(rel) = serializer.relationship_owned(&self_link, &name, ids) {
366 object = object.relationship(name, rel);
367 }
368 }
369
370 object.with_links(Links::this(self_link))
371 }
372}