fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! JSON:API resource types: which table holds them, their attributes and relationships, and the
//! descriptions the OpenAPI document shows. [`crate::query::ApiQuery`] reads and renders them.

use serde_json::{Map, Value};

/// What an attribute holds, which decides how it is rendered and how OpenAPI describes it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Kind {
    /// Text.
    String,
    /// A whole number.
    Integer,
    /// A number that may have a fraction.
    Number,
    /// `true` or `false`. Databases that store booleans as 0 and 1 are read as booleans.
    Boolean,
    /// A moment in time, rendered as `2026-11-30T09:00:00.000000Z`, as Laravel renders dates.
    Timestamp,
    /// A JSON value, stored as JSON text.
    Json,
}

/// One attribute of a resource type.
#[derive(Debug, Clone)]
pub struct Attribute {
    pub(crate) name: String,
    pub(crate) column: String,
    pub(crate) kind: Kind,
    pub(crate) nullable: bool,
}

/// How a relationship's records are found.
#[derive(Debug, Clone)]
pub(crate) enum Link {
    /// This table's `foreign_key` holds the related record's key.
    BelongsTo { foreign_key: String },
    /// The related table's `foreign_key` holds this record's key.
    HasMany { foreign_key: String },
}

/// One relationship of a resource type.
#[derive(Debug, Clone)]
pub struct Relationship {
    pub(crate) name: String,
    pub(crate) related: String,
    pub(crate) link: Link,
}

/// A field's description, and for an attribute with fixed values, what each value means.
#[derive(Debug, Clone, Default)]
pub(crate) struct Description {
    pub(crate) text: String,
    pub(crate) values: Vec<(String, String)>,
}

/// A JSON:API resource type stored in one table, such as `orders`.
///
/// ```
/// use fusion_stack::resources::{Kind, Resource};
///
/// let orders = Resource::new("orders", "orders")
///     .attribute("reference", Kind::String)
///     .attribute("total_cents", Kind::Integer)
///     .attribute("created_at", Kind::Timestamp)
///     .belongs_to("customer", "customers", "customer_id")
///     .describe("total_cents", "The order total in the smallest unit of the currency.");
/// ```
#[derive(Debug, Clone)]
pub struct Resource {
    pub(crate) kind: String,
    pub(crate) table: String,
    pub(crate) key: String,
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) relationships: Vec<Relationship>,
    pub(crate) descriptions: Vec<(String, Description)>,
}

impl Resource {
    /// A resource type, such as `orders`, whose records are rows of `table`, keyed by `id`.
    #[must_use]
    pub fn new(kind: &str, table: &str) -> Self {
        Self {
            kind: kind.to_owned(),
            table: table.to_owned(),
            key: "id".to_owned(),
            attributes: Vec::new(),
            relationships: Vec::new(),
            descriptions: Vec::new(),
        }
    }

    /// The column holding each record's ID, when it is not `id`.
    #[must_use]
    pub fn key(mut self, column: &str) -> Self {
        column.clone_into(&mut self.key);
        self
    }

    /// An attribute read from the column of the same name. Attributes render in the order they
    /// are added.
    #[must_use]
    pub fn attribute(self, name: &str, kind: Kind) -> Self {
        self.attribute_from(name, name, kind)
    }

    /// An attribute read from a column with another name.
    #[must_use]
    pub fn attribute_from(mut self, name: &str, column: &str, kind: Kind) -> Self {
        self.attributes.push(Attribute {
            name: name.to_owned(),
            column: column.to_owned(),
            kind,
            nullable: false,
        });
        self
    }

    /// Marks the last added attribute as one that may be `null`.
    #[must_use]
    pub fn nullable(mut self) -> Self {
        if let Some(attribute) = self.attributes.last_mut() {
            attribute.nullable = true;
        }
        self
    }

    /// A to-one relationship: this table's `foreign_key` column holds the related record's key.
    #[must_use]
    pub fn belongs_to(mut self, name: &str, related: &str, foreign_key: &str) -> Self {
        self.relationships.push(Relationship {
            name: name.to_owned(),
            related: related.to_owned(),
            link: Link::BelongsTo {
                foreign_key: foreign_key.to_owned(),
            },
        });
        self
    }

    /// A to-many relationship: the related table's `foreign_key` column holds this record's key.
    /// Related records are listed by key.
    #[must_use]
    pub fn has_many(mut self, name: &str, related: &str, foreign_key: &str) -> Self {
        self.relationships.push(Relationship {
            name: name.to_owned(),
            related: related.to_owned(),
            link: Link::HasMany {
                foreign_key: foreign_key.to_owned(),
            },
        });
        self
    }

    /// Describes an attribute or relationship in the OpenAPI document, as PHP's `#[Describe]` does.
    #[must_use]
    pub fn describe(mut self, field: &str, text: &str) -> Self {
        self.description_mut(field).text = text.to_owned();
        self
    }

    /// Describes an attribute with fixed values, and what each value means.
    #[must_use]
    pub fn describe_values<I, V, D>(mut self, field: &str, text: &str, values: I) -> Self
    where
        I: IntoIterator<Item = (V, D)>,
        V: Into<String>,
        D: Into<String>,
    {
        let description = self.description_mut(field);
        description.text = text.to_owned();
        description.values = values
            .into_iter()
            .map(|(value, meaning)| (value.into(), meaning.into()))
            .collect();
        self
    }

    fn description_mut(&mut self, field: &str) -> &mut Description {
        if let Some(index) = self.descriptions.iter().position(|(name, _)| name == field) {
            return &mut self.descriptions[index].1;
        }
        self.descriptions
            .push((field.to_owned(), Description::default()));
        let last = self.descriptions.len() - 1;
        &mut self.descriptions[last].1
    }

    pub(crate) fn relationship(&self, name: &str) -> Option<&Relationship> {
        self.relationships
            .iter()
            .find(|relationship| relationship.name == name)
    }

    /// The type's name, such as `orders`.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.kind
    }

    /// Renders a row as a resource object, with the attributes `fields` allows (all of them when
    /// `None`) and the given relationships.
    pub(crate) fn object(
        &self,
        row: &Map<String, Value>,
        fields: Option<&[String]>,
        relationships: Option<Map<String, Value>>,
    ) -> Value {
        let mut object = Map::new();
        object.insert("id".into(), Value::String(id_of(row, &self.key)));
        object.insert("type".into(), Value::String(self.kind.clone()));
        let mut attributes = Map::new();
        for attribute in &self.attributes {
            if fields.is_some_and(|fields| !fields.iter().any(|field| field == &attribute.name)) {
                continue;
            }
            let value = row.get(&attribute.column).cloned().unwrap_or(Value::Null);
            attributes.insert(attribute.name.clone(), render(attribute.kind, value));
        }
        if !attributes.is_empty() {
            object.insert("attributes".into(), Value::Object(attributes));
        }
        if let Some(relationships) = relationships.filter(|relationships| !relationships.is_empty())
        {
            object.insert("relationships".into(), Value::Object(relationships));
        }
        Value::Object(object)
    }
}

/// A row's key as a JSON:API ID: always a string.
pub(crate) fn id_of(row: &Map<String, Value>, key: &str) -> String {
    match row.get(key) {
        Some(Value::String(id)) => id.clone(),
        Some(Value::Null) | None => String::new(),
        Some(other) => other.to_string(),
    }
}

/// A stored value as its attribute kind renders it.
pub(crate) fn render(kind: Kind, value: Value) -> Value {
    match (kind, value) {
        (_, Value::Null) => Value::Null,
        (Kind::Integer, Value::String(text)) => {
            text.parse::<i64>().map_or(Value::String(text), Value::from)
        }
        (Kind::Number, Value::String(text)) => {
            text.parse::<f64>().map_or(Value::String(text), Value::from)
        }
        (Kind::Boolean, Value::Number(number)) => Value::Bool(number.as_f64() != Some(0.0)),
        (Kind::Boolean, Value::String(text)) => {
            Value::Bool(!matches!(text.as_str(), "" | "0" | "false"))
        }
        (Kind::Timestamp, Value::String(text)) => Value::String(timestamp(&text).unwrap_or(text)),
        (Kind::Json, Value::String(text)) => {
            serde_json::from_str(&text).unwrap_or(Value::String(text))
        }
        (_, value) => value,
    }
}

/// A stored time as Laravel renders dates: `2026-11-30T09:00:00.000000Z`. Stored times are
/// RFC 3339, or `2026-11-30 09:00:00` in UTC as Laravel stores them.
pub(crate) fn timestamp(text: &str) -> Option<String> {
    use laravel::time::Timestamp;

    let moment = text
        .parse::<Timestamp>()
        .or_else(|_| format!("{}Z", text.replace(' ', "T")).parse::<Timestamp>())
        .ok()?;
    Some(format!(
        "{}.{:06}Z",
        moment.strftime("%Y-%m-%dT%H:%M:%S"),
        moment.subsec_microsecond()
    ))
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn times_render_as_laravel_renders_dates() {
        assert_eq!(
            timestamp("2026-12-01T20:10:37.099918+00:00").as_deref(),
            Some("2026-12-01T20:10:37.099918Z")
        );
        assert_eq!(
            timestamp("2026-12-01 18:52:23").as_deref(),
            Some("2026-12-01T18:52:23.000000Z")
        );
        assert_eq!(
            timestamp("2026-12-01T21:00:00+01:00").as_deref(),
            Some("2026-12-01T20:00:00.000000Z")
        );
    }

    #[test]
    fn objects_keep_attribute_order_and_drop_empty_members() {
        let orders = Resource::new("orders", "orders")
            .attribute("status", Kind::String)
            .attribute("total_cents", Kind::Integer)
            .attribute_from("paid", "is_paid", Kind::Boolean);
        let row = json!({ "id": 7, "status": "paid", "total_cents": "1200", "is_paid": 1 });
        let row = row.as_object().unwrap();
        assert_eq!(
            serde_json::to_string(&orders.object(row, None, None)).unwrap(),
            r#"{"id":"7","type":"orders","attributes":{"status":"paid","total_cents":1200,"paid":true}}"#
        );
        assert_eq!(
            orders.object(row, Some(&["customer".to_owned()]), None),
            json!({ "id": "7", "type": "orders" })
        );
    }
}