Skip to main content

ash_jsonapi/
document.rs

1//! Pure JSON:API document types.
2//!
3//! These carry no dependency on axum or any data layer, so they work with
4//! `default-features = false`.
5
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9/// A JSON:API top-level document.
10///
11/// Exactly one of `data` or `errors` is present in a valid document; the
12/// constructors below are the supported way to build one.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub struct Document {
15    #[serde(skip_serializing_if = "Option::is_none")]
16    pub data: Option<PrimaryData>,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub errors: Option<Vec<ErrorObject>>,
19    /// Compound-document sidecar, populated by `?include=`.
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub included: Option<Vec<ResourceObject>>,
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub links: Option<Links>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub meta: Option<BTreeMap<String, serde_json::Value>>,
26}
27
28impl Document {
29    /// A document whose primary data is a single resource.
30    pub fn single(resource: ResourceObject) -> Self {
31        Self {
32            data: Some(PrimaryData::Single(Box::new(resource))),
33            ..Self::empty()
34        }
35    }
36
37    /// A document whose primary data is a collection — a listing response.
38    pub fn collection(resources: Vec<ResourceObject>) -> Self {
39        Self {
40            data: Some(PrimaryData::Collection(resources)),
41            ..Self::empty()
42        }
43    }
44
45    /// An error document. JSON:API allows several errors per response.
46    pub fn errors(errors: Vec<ErrorObject>) -> Self {
47        Self {
48            errors: Some(errors),
49            ..Self::empty()
50        }
51    }
52
53    /// Attach top-level links — pagination links on a listing, for instance.
54    pub fn with_links(mut self, links: Links) -> Self {
55        self.links = Some(links);
56        self
57    }
58
59    /// Attach compound-document resources, as requested by `?include=`.
60    pub fn with_included(mut self, included: Vec<ResourceObject>) -> Self {
61        self.included = Some(included);
62        self
63    }
64
65    /// Set one top-level `meta` member.
66    ///
67    /// Creates the `meta` object if the document has none, so members
68    /// accumulate rather than replacing one another — a paged listing keeps
69    /// its `total` when a `lang` is added beside it.
70    #[must_use]
71    pub fn with_meta(
72        mut self,
73        key: impl Into<String>,
74        value: impl Into<serde_json::Value>,
75    ) -> Self {
76        self.meta
77            .get_or_insert_with(BTreeMap::new)
78            .insert(key.into(), value.into());
79        self
80    }
81
82    fn empty() -> Self {
83        Self {
84            data: None,
85            errors: None,
86            included: None,
87            links: None,
88            meta: None,
89        }
90    }
91}
92
93/// Top-level `data`: one resource, a collection, or an explicit null.
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95#[serde(untagged)]
96pub enum PrimaryData {
97    Single(Box<ResourceObject>),
98    Collection(Vec<ResourceObject>),
99}
100
101/// A JSON:API resource object.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103pub struct ResourceObject {
104    /// The resource type — `ResourceSchema::name`.
105    #[serde(rename = "type")]
106    pub kind: String,
107    /// Absent on a client-generated create, present everywhere else.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub id: Option<String>,
110    /// A redacted or unrequested attribute is *absent*, never `null`.
111    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
112    pub attributes: BTreeMap<String, serde_json::Value>,
113    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
114    pub relationships: BTreeMap<String, Relationship>,
115    /// Aggregates land here — `ResourceSchema::aggregates`.
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub meta: Option<BTreeMap<String, serde_json::Value>>,
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub links: Option<Links>,
120}
121
122impl ResourceObject {
123    pub fn new(kind: impl Into<String>, id: impl Into<String>) -> Self {
124        Self {
125            kind: kind.into(),
126            id: Some(id.into()),
127            attributes: BTreeMap::new(),
128            relationships: BTreeMap::new(),
129            meta: None,
130            links: None,
131        }
132    }
133
134    pub fn attr(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
135        self.attributes.insert(key.into(), value.into());
136        self
137    }
138
139    pub fn relationship(mut self, name: impl Into<String>, rel: Relationship) -> Self {
140        self.relationships.insert(name.into(), rel);
141        self
142    }
143
144    pub fn with_links(mut self, links: Links) -> Self {
145        self.links = Some(links);
146        self
147    }
148}
149
150/// A relationship: linkage plus its `self`/`related` links.
151#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152pub struct Relationship {
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub data: Option<Linkage>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub links: Option<Links>,
157}
158
159impl Relationship {
160    /// A to-one relationship — `todo` belongs_to `user` as `owner`.
161    pub fn to_one(identifier: ResourceIdentifier) -> Self {
162        Self {
163            data: Some(Linkage::One(Some(identifier))),
164            links: None,
165        }
166    }
167
168    /// A to-many relationship — `user` has_many `todo`.
169    pub fn to_many(identifiers: Vec<ResourceIdentifier>) -> Self {
170        Self {
171            data: Some(Linkage::Many(identifiers)),
172            links: None,
173        }
174    }
175
176    /// An empty to-one relationship — an explicit `null`, distinct from absent.
177    pub fn empty_to_one() -> Self {
178        Self {
179            data: Some(Linkage::One(None)),
180            links: None,
181        }
182    }
183
184    pub fn with_links(mut self, links: Links) -> Self {
185        self.links = Some(links);
186        self
187    }
188}
189
190/// Relationship linkage. `One(None)` serializes as `null`.
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
192#[serde(untagged)]
193pub enum Linkage {
194    One(Option<ResourceIdentifier>),
195    Many(Vec<ResourceIdentifier>),
196}
197
198/// A `{ type, id }` pair.
199#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
200pub struct ResourceIdentifier {
201    #[serde(rename = "type")]
202    pub kind: String,
203    pub id: String,
204}
205
206impl ResourceIdentifier {
207    pub fn new(kind: impl Into<String>, id: impl Into<String>) -> Self {
208        Self {
209            kind: kind.into(),
210            id: id.into(),
211        }
212    }
213}
214
215/// A links object. Only the members JSON:API defines for our responses.
216#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
217pub struct Links {
218    #[serde(rename = "self", skip_serializing_if = "Option::is_none")]
219    pub this: Option<String>,
220    #[serde(skip_serializing_if = "Option::is_none")]
221    pub related: Option<String>,
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub first: Option<String>,
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub prev: Option<String>,
226    #[serde(skip_serializing_if = "Option::is_none")]
227    pub next: Option<String>,
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub last: Option<String>,
230}
231
232impl Links {
233    pub fn this(url: impl Into<String>) -> Self {
234        Self {
235            this: Some(url.into()),
236            ..Self::default()
237        }
238    }
239
240    pub fn related(mut self, url: impl Into<String>) -> Self {
241        self.related = Some(url.into());
242        self
243    }
244
245    pub fn first(mut self, url: impl Into<String>) -> Self {
246        self.first = Some(url.into());
247        self
248    }
249
250    pub fn next(mut self, url: impl Into<String>) -> Self {
251        self.next = Some(url.into());
252        self
253    }
254
255    pub fn prev(mut self, url: impl Into<String>) -> Self {
256        self.prev = Some(url.into());
257        self
258    }
259
260    pub fn last(mut self, url: impl Into<String>) -> Self {
261        self.last = Some(url.into());
262        self
263    }
264}
265
266/// A JSON:API error object.
267#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
268pub struct ErrorObject {
269    /// The correlation id from the current `ash-log` scope.
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub id: Option<String>,
272    pub status: String,
273    pub code: String,
274    pub title: String,
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub detail: Option<String>,
277    #[serde(skip_serializing_if = "Option::is_none")]
278    pub source: Option<ErrorSource>,
279    /// Non-standard members, which JSON:API confines to `meta`.
280    ///
281    /// Carries `i18n` — a [`Translation`](crate::i18n::Translation) key and
282    /// its params — when the error was given one, so a client can render the
283    /// failure in its own language instead of matching on English `detail`.
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub meta: Option<BTreeMap<String, serde_json::Value>>,
286}
287
288/// Points at whatever caused the error — a body member or a query parameter.
289#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
290pub struct ErrorSource {
291    /// A JSON pointer, e.g. `/data/attributes/message`.
292    #[serde(skip_serializing_if = "Option::is_none")]
293    pub pointer: Option<String>,
294    /// A query parameter, e.g. `sort`.
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub parameter: Option<String>,
297}
298
299impl ErrorSource {
300    pub fn pointer(p: impl Into<String>) -> Self {
301        Self {
302            pointer: Some(p.into()),
303            parameter: None,
304        }
305    }
306
307    pub fn parameter(p: impl Into<String>) -> Self {
308        Self {
309            pointer: None,
310            parameter: Some(p.into()),
311        }
312    }
313}
314
315/// The JSON:API media type. Every request and response carries it.
316pub const MEDIA_TYPE: &str = "application/vnd.api+json";