1use serde_json::{Map, Value};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum Kind {
10 String,
12 Integer,
14 Number,
16 Boolean,
18 Timestamp,
20 Json,
22}
23
24#[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#[derive(Debug, Clone)]
35pub(crate) enum Link {
36 BelongsTo { foreign_key: String },
38 HasMany { foreign_key: String },
40}
41
42#[derive(Debug, Clone)]
44pub struct Relationship {
45 pub(crate) name: String,
46 pub(crate) related: String,
47 pub(crate) link: Link,
48}
49
50#[derive(Debug, Clone, Default)]
52pub(crate) struct Description {
53 pub(crate) text: String,
54 pub(crate) values: Vec<(String, String)>,
55}
56
57#[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 #[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 #[must_use]
95 pub fn key(mut self, column: &str) -> Self {
96 column.clone_into(&mut self.key);
97 self
98 }
99
100 #[must_use]
103 pub fn attribute(self, name: &str, kind: Kind) -> Self {
104 self.attribute_from(name, name, kind)
105 }
106
107 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
197 pub fn name(&self) -> &str {
198 &self.kind
199 }
200
201 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
231pub(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
240pub(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
262pub(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}