Skip to main content

fusion_stack/
resources.rs

1//! JSON:API resource types: which table holds them, their attributes and relationships, and the
2//! descriptions the OpenAPI document shows. [`crate::query::ApiQuery`] reads and renders them.
3
4use serde_json::{Map, Value};
5
6/// What an attribute holds, which decides how it is rendered and how OpenAPI describes it.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum Kind {
10    /// Text.
11    String,
12    /// A whole number.
13    Integer,
14    /// A number that may have a fraction.
15    Number,
16    /// `true` or `false`. Databases that store booleans as 0 and 1 are read as booleans.
17    Boolean,
18    /// A moment in time, rendered as `2026-11-30T09:00:00.000000Z`, as Laravel renders dates.
19    Timestamp,
20    /// A JSON value, stored as JSON text.
21    Json,
22}
23
24/// One attribute of a resource type.
25#[derive(Debug, Clone)]
26pub struct Attribute {
27    pub(crate) name: String,
28    pub(crate) column: String,
29    pub(crate) kind: Kind,
30    pub(crate) nullable: bool,
31}
32
33/// How a relationship's records are found.
34#[derive(Debug, Clone)]
35pub(crate) enum Link {
36    /// This table's `foreign_key` holds the related record's key.
37    BelongsTo { foreign_key: String },
38    /// The related table's `foreign_key` holds this record's key.
39    HasMany { foreign_key: String },
40}
41
42/// One relationship of a resource type.
43#[derive(Debug, Clone)]
44pub struct Relationship {
45    pub(crate) name: String,
46    pub(crate) related: String,
47    pub(crate) link: Link,
48}
49
50/// A field's description, and for an attribute with fixed values, what each value means.
51#[derive(Debug, Clone, Default)]
52pub(crate) struct Description {
53    pub(crate) text: String,
54    pub(crate) values: Vec<(String, String)>,
55}
56
57/// A JSON:API resource type stored in one table, such as `orders`.
58///
59/// ```
60/// use fusion_stack::resources::{Kind, Resource};
61///
62/// let orders = Resource::new("orders", "orders")
63///     .attribute("reference", Kind::String)
64///     .attribute("total_cents", Kind::Integer)
65///     .attribute("created_at", Kind::Timestamp)
66///     .belongs_to("customer", "customers", "customer_id")
67///     .describe("total_cents", "The order total in the smallest unit of the currency.");
68/// ```
69#[derive(Debug, Clone)]
70pub struct Resource {
71    pub(crate) kind: String,
72    pub(crate) table: String,
73    pub(crate) key: String,
74    pub(crate) attributes: Vec<Attribute>,
75    pub(crate) relationships: Vec<Relationship>,
76    pub(crate) descriptions: Vec<(String, Description)>,
77}
78
79impl Resource {
80    /// A resource type, such as `orders`, whose records are rows of `table`, keyed by `id`.
81    #[must_use]
82    pub fn new(kind: &str, table: &str) -> Self {
83        Self {
84            kind: kind.to_owned(),
85            table: table.to_owned(),
86            key: "id".to_owned(),
87            attributes: Vec::new(),
88            relationships: Vec::new(),
89            descriptions: Vec::new(),
90        }
91    }
92
93    /// The column holding each record's ID, when it is not `id`.
94    #[must_use]
95    pub fn key(mut self, column: &str) -> Self {
96        column.clone_into(&mut self.key);
97        self
98    }
99
100    /// An attribute read from the column of the same name. Attributes render in the order they
101    /// are added.
102    #[must_use]
103    pub fn attribute(self, name: &str, kind: Kind) -> Self {
104        self.attribute_from(name, name, kind)
105    }
106
107    /// An attribute read from a column with another name.
108    #[must_use]
109    pub fn attribute_from(mut self, name: &str, column: &str, kind: Kind) -> Self {
110        self.attributes.push(Attribute {
111            name: name.to_owned(),
112            column: column.to_owned(),
113            kind,
114            nullable: false,
115        });
116        self
117    }
118
119    /// Marks the last added attribute as one that may be `null`.
120    #[must_use]
121    pub fn nullable(mut self) -> Self {
122        if let Some(attribute) = self.attributes.last_mut() {
123            attribute.nullable = true;
124        }
125        self
126    }
127
128    /// A to-one relationship: this table's `foreign_key` column holds the related record's key.
129    #[must_use]
130    pub fn belongs_to(mut self, name: &str, related: &str, foreign_key: &str) -> Self {
131        self.relationships.push(Relationship {
132            name: name.to_owned(),
133            related: related.to_owned(),
134            link: Link::BelongsTo {
135                foreign_key: foreign_key.to_owned(),
136            },
137        });
138        self
139    }
140
141    /// A to-many relationship: the related table's `foreign_key` column holds this record's key.
142    /// Related records are listed by key.
143    #[must_use]
144    pub fn has_many(mut self, name: &str, related: &str, foreign_key: &str) -> Self {
145        self.relationships.push(Relationship {
146            name: name.to_owned(),
147            related: related.to_owned(),
148            link: Link::HasMany {
149                foreign_key: foreign_key.to_owned(),
150            },
151        });
152        self
153    }
154
155    /// Describes an attribute or relationship in the OpenAPI document, as PHP's `#[Describe]` does.
156    #[must_use]
157    pub fn describe(mut self, field: &str, text: &str) -> Self {
158        self.description_mut(field).text = text.to_owned();
159        self
160    }
161
162    /// Describes an attribute with fixed values, and what each value means.
163    #[must_use]
164    pub fn describe_values<I, V, D>(mut self, field: &str, text: &str, values: I) -> Self
165    where
166        I: IntoIterator<Item = (V, D)>,
167        V: Into<String>,
168        D: Into<String>,
169    {
170        let description = self.description_mut(field);
171        description.text = text.to_owned();
172        description.values = values
173            .into_iter()
174            .map(|(value, meaning)| (value.into(), meaning.into()))
175            .collect();
176        self
177    }
178
179    fn description_mut(&mut self, field: &str) -> &mut Description {
180        if let Some(index) = self.descriptions.iter().position(|(name, _)| name == field) {
181            return &mut self.descriptions[index].1;
182        }
183        self.descriptions
184            .push((field.to_owned(), Description::default()));
185        let last = self.descriptions.len() - 1;
186        &mut self.descriptions[last].1
187    }
188
189    pub(crate) fn relationship(&self, name: &str) -> Option<&Relationship> {
190        self.relationships
191            .iter()
192            .find(|relationship| relationship.name == name)
193    }
194
195    /// The type's name, such as `orders`.
196    #[must_use]
197    pub fn name(&self) -> &str {
198        &self.kind
199    }
200
201    /// Renders a row as a resource object, with the attributes `fields` allows (all of them when
202    /// `None`) and the given relationships.
203    pub(crate) fn object(
204        &self,
205        row: &Map<String, Value>,
206        fields: Option<&[String]>,
207        relationships: Option<Map<String, Value>>,
208    ) -> Value {
209        let mut object = Map::new();
210        object.insert("id".into(), Value::String(id_of(row, &self.key)));
211        object.insert("type".into(), Value::String(self.kind.clone()));
212        let mut attributes = Map::new();
213        for attribute in &self.attributes {
214            if fields.is_some_and(|fields| !fields.iter().any(|field| field == &attribute.name)) {
215                continue;
216            }
217            let value = row.get(&attribute.column).cloned().unwrap_or(Value::Null);
218            attributes.insert(attribute.name.clone(), render(attribute.kind, value));
219        }
220        if !attributes.is_empty() {
221            object.insert("attributes".into(), Value::Object(attributes));
222        }
223        if let Some(relationships) = relationships.filter(|relationships| !relationships.is_empty())
224        {
225            object.insert("relationships".into(), Value::Object(relationships));
226        }
227        Value::Object(object)
228    }
229}
230
231/// A row's key as a JSON:API ID: always a string.
232pub(crate) fn id_of(row: &Map<String, Value>, key: &str) -> String {
233    match row.get(key) {
234        Some(Value::String(id)) => id.clone(),
235        Some(Value::Null) | None => String::new(),
236        Some(other) => other.to_string(),
237    }
238}
239
240/// A stored value as its attribute kind renders it.
241pub(crate) fn render(kind: Kind, value: Value) -> Value {
242    match (kind, value) {
243        (_, Value::Null) => Value::Null,
244        (Kind::Integer, Value::String(text)) => {
245            text.parse::<i64>().map_or(Value::String(text), Value::from)
246        }
247        (Kind::Number, Value::String(text)) => {
248            text.parse::<f64>().map_or(Value::String(text), Value::from)
249        }
250        (Kind::Boolean, Value::Number(number)) => Value::Bool(number.as_f64() != Some(0.0)),
251        (Kind::Boolean, Value::String(text)) => {
252            Value::Bool(!matches!(text.as_str(), "" | "0" | "false"))
253        }
254        (Kind::Timestamp, Value::String(text)) => Value::String(timestamp(&text).unwrap_or(text)),
255        (Kind::Json, Value::String(text)) => {
256            serde_json::from_str(&text).unwrap_or(Value::String(text))
257        }
258        (_, value) => value,
259    }
260}
261
262/// A stored time as Laravel renders dates: `2026-11-30T09:00:00.000000Z`. Stored times are
263/// RFC 3339, or `2026-11-30 09:00:00` in UTC as Laravel stores them.
264pub(crate) fn timestamp(text: &str) -> Option<String> {
265    use laravel::time::Timestamp;
266
267    let moment = text
268        .parse::<Timestamp>()
269        .or_else(|_| format!("{}Z", text.replace(' ', "T")).parse::<Timestamp>())
270        .ok()?;
271    Some(format!(
272        "{}.{:06}Z",
273        moment.strftime("%Y-%m-%dT%H:%M:%S"),
274        moment.subsec_microsecond()
275    ))
276}
277
278#[cfg(test)]
279mod tests {
280    use serde_json::json;
281
282    use super::*;
283
284    #[test]
285    fn times_render_as_laravel_renders_dates() {
286        assert_eq!(
287            timestamp("2026-12-01T20:10:37.099918+00:00").as_deref(),
288            Some("2026-12-01T20:10:37.099918Z")
289        );
290        assert_eq!(
291            timestamp("2026-12-01 18:52:23").as_deref(),
292            Some("2026-12-01T18:52:23.000000Z")
293        );
294        assert_eq!(
295            timestamp("2026-12-01T21:00:00+01:00").as_deref(),
296            Some("2026-12-01T20:00:00.000000Z")
297        );
298    }
299
300    #[test]
301    fn objects_keep_attribute_order_and_drop_empty_members() {
302        let orders = Resource::new("orders", "orders")
303            .attribute("status", Kind::String)
304            .attribute("total_cents", Kind::Integer)
305            .attribute_from("paid", "is_paid", Kind::Boolean);
306        let row = json!({ "id": 7, "status": "paid", "total_cents": "1200", "is_paid": 1 });
307        let row = row.as_object().unwrap();
308        assert_eq!(
309            serde_json::to_string(&orders.object(row, None, None)).unwrap(),
310            r#"{"id":"7","type":"orders","attributes":{"status":"paid","total_cents":1200,"paid":true}}"#
311        );
312        assert_eq!(
313            orders.object(row, Some(&["customer".to_owned()]), None),
314            json!({ "id": "7", "type": "orders" })
315        );
316    }
317}