use serde_json::{Map, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Kind {
String,
Integer,
Number,
Boolean,
Timestamp,
Json,
}
#[derive(Debug, Clone)]
pub struct Attribute {
pub(crate) name: String,
pub(crate) column: String,
pub(crate) kind: Kind,
pub(crate) nullable: bool,
}
#[derive(Debug, Clone)]
pub(crate) enum Link {
BelongsTo { foreign_key: String },
HasMany { foreign_key: String },
}
#[derive(Debug, Clone)]
pub struct Relationship {
pub(crate) name: String,
pub(crate) related: String,
pub(crate) link: Link,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Description {
pub(crate) text: String,
pub(crate) values: Vec<(String, String)>,
}
#[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 {
#[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(),
}
}
#[must_use]
pub fn key(mut self, column: &str) -> Self {
column.clone_into(&mut self.key);
self
}
#[must_use]
pub fn attribute(self, name: &str, kind: Kind) -> Self {
self.attribute_from(name, name, kind)
}
#[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
}
#[must_use]
pub fn nullable(mut self) -> Self {
if let Some(attribute) = self.attributes.last_mut() {
attribute.nullable = true;
}
self
}
#[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
}
#[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
}
#[must_use]
pub fn describe(mut self, field: &str, text: &str) -> Self {
self.description_mut(field).text = text.to_owned();
self
}
#[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)
}
#[must_use]
pub fn name(&self) -> &str {
&self.kind
}
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)
}
}
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(),
}
}
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,
}
}
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" })
);
}
}