1use std::collections::HashMap;
2
3use serde::Serialize;
4use serde_json::{json, Value};
5
6pub trait SerializesToArray: Send + Sync + Serialize {
29 fn hidden() -> Vec<&'static str>
31 where
32 Self: Sized,
33 {
34 vec![]
35 }
36
37 fn appends() -> Vec<&'static str>
39 where
40 Self: Sized,
41 {
42 vec![]
43 }
44
45 fn get_appended(&self, _key: &str) -> Option<Value> {
49 None
50 }
51
52 fn to_array(&self) -> Value
54 where
55 Self: Sized,
56 {
57 let mut value = serde_json::to_value(self).unwrap_or(Value::Null);
58 if let Value::Object(ref mut map) = value {
59 for key in Self::hidden() {
60 map.remove(key);
61 }
62 for key in Self::appends() {
63 if let Some(val) = self.get_appended(key) {
64 map.insert(key.to_string(), val);
65 }
66 }
67 }
68 value
69 }
70
71 fn to_json(&self) -> Result<String, serde_json::Error>
73 where
74 Self: Sized,
75 {
76 serde_json::to_string_pretty(&self.to_array())
77 }
78
79 fn to_json_compact(&self) -> Result<String, serde_json::Error>
81 where
82 Self: Sized,
83 {
84 serde_json::to_string(&self.to_array())
85 }
86}
87
88pub trait ApiResource<T: Serialize + Send + Sync + 'static>: Sized {
111 fn transform(model: &T) -> Value;
113
114 fn make(model: T) -> JsonResource<T, Self> {
116 JsonResource {
117 inner: model,
118 _marker: std::marker::PhantomData,
119 }
120 }
121
122 fn collection(models: Vec<T>) -> ResourceCollection<T, Self> {
124 ResourceCollection {
125 inner: models,
126 _marker: std::marker::PhantomData,
127 }
128 }
129}
130
131pub struct JsonResource<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> {
135 inner: T,
136 _marker: std::marker::PhantomData<R>,
137}
138
139impl<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> JsonResource<T, R> {
140 pub fn to_array(&self) -> Value {
142 R::transform(&self.inner)
143 }
144
145 pub fn to_json(&self) -> Result<String, serde_json::Error> {
147 serde_json::to_string_pretty(&self.to_array())
148 }
149
150 pub fn into_inner(self) -> T {
152 self.inner
153 }
154}
155
156pub struct ResourceCollection<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> {
163 inner: Vec<T>,
164 _marker: std::marker::PhantomData<R>,
165}
166
167impl<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> ResourceCollection<T, R> {
168 pub fn to_array(&self) -> Value {
172 let data: Vec<Value> = self.inner.iter().map(|item| R::transform(item)).collect();
173 json!({
174 "data": data,
175 "meta": {
176 "count": self.inner.len(),
177 }
178 })
179 }
180
181 pub fn to_json(&self) -> Result<String, serde_json::Error> {
183 serde_json::to_string_pretty(&self.to_array())
184 }
185
186 pub fn with_meta(self, extra: HashMap<String, Value>) -> Value {
188 let mut base = self.to_array();
189 if let Value::Object(ref mut map) = base {
190 if let Some(Value::Object(ref mut meta)) = map.get_mut("meta") {
191 for (k, v) in extra {
192 meta.insert(k, v);
193 }
194 }
195 }
196 base
197 }
198
199 pub fn into_inner(self) -> Vec<T> {
201 self.inner
202 }
203}
204
205#[cfg(test)]
210mod tests {
211 use super::*;
212 use std::collections::HashMap;
213
214 use serde::Serialize;
215
216 #[derive(Debug, Clone, Serialize)]
217 struct User {
218 id: u64,
219 name: String,
220 email: String,
221 password: String,
222 }
223
224 impl SerializesToArray for User {
225 fn hidden() -> Vec<&'static str> {
226 vec!["password"]
227 }
228
229 fn appends() -> Vec<&'static str> {
230 vec!["greeting"]
231 }
232
233 fn get_appended(&self, key: &str) -> Option<Value> {
234 match key {
235 "greeting" => Some(json!("Hello, ".to_string() + &self.name)),
236 _ => None,
237 }
238 }
239 }
240
241 #[test]
242 fn test_to_array_hides_fields() {
243 let user = User {
244 id: 1,
245 name: "Alice".into(),
246 email: "alice@test.com".into(),
247 password: "secret".into(),
248 };
249 let arr = user.to_array();
250 assert!(arr.get("password").is_none());
251 assert_eq!(arr.get("id").and_then(|v| v.as_u64()), Some(1));
252 assert_eq!(arr.get("name").and_then(|v| v.as_str()), Some("Alice"));
253 }
254
255 #[test]
256 fn test_to_array_appends_fields() {
257 let user = User {
258 id: 2,
259 name: "Bob".into(),
260 email: "bob@test.com".into(),
261 password: "hunter2".into(),
262 };
263 let arr = user.to_array();
264 assert_eq!(
265 arr.get("greeting").and_then(|v| v.as_str()),
266 Some("Hello, Bob")
267 );
268 }
269
270 #[test]
271 fn test_to_json_roundtrip() {
272 let user = User {
273 id: 3,
274 name: "Charlie".into(),
275 email: "charlie@test.com".into(),
276 password: "p4ss".into(),
277 };
278 let json_str = user.to_json().unwrap();
279 let parsed: Value = serde_json::from_str(&json_str).unwrap();
280 assert_eq!(parsed.get("id").and_then(|v| v.as_u64()), Some(3));
281 assert!(parsed.get("password").is_none());
282 }
283
284 #[test]
285 fn test_to_json_compact_no_newlines() {
286 let user = User {
287 id: 1,
288 name: "Diana".into(),
289 email: "diana@test.com".into(),
290 password: "x".into(),
291 };
292 let compact = user.to_json_compact().unwrap();
293 assert!(!compact.contains('\n'));
294 assert!(compact.contains("Diana"));
295 }
296
297 #[test]
298 fn test_default_hidden_and_appends() {
299 #[derive(Debug, Clone, Serialize)]
300 struct Simple {
301 id: u64,
302 label: String,
303 }
304
305 impl SerializesToArray for Simple {}
306
307 let s = Simple {
308 id: 10,
309 label: "test".into(),
310 };
311 let arr = s.to_array();
312 assert_eq!(arr.get("id").and_then(|v| v.as_u64()), Some(10));
313 assert_eq!(arr.get("label").and_then(|v| v.as_str()), Some("test"));
314 }
315
316 #[derive(Debug, Clone, Serialize)]
321 struct Product {
322 sku: String,
323 price: f64,
324 internal_note: String,
325 }
326
327 struct ProductResource;
328
329 impl ApiResource<Product> for ProductResource {
330 fn transform(model: &Product) -> Value {
331 json!({
332 "sku": model.sku,
333 "price": model.price,
334 })
335 }
336 }
337
338 #[test]
339 fn test_json_resource_to_array() {
340 let product = Product {
341 sku: "ABC-123".into(),
342 price: 29.99,
343 internal_note: "ignore me".into(),
344 };
345 let resource = ProductResource::make(product);
346 let arr = resource.to_array();
347 assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("ABC-123"));
348 assert_eq!(arr.get("price").and_then(|v| v.as_f64()), Some(29.99));
349 assert!(arr.get("internal_note").is_none());
350 }
351
352 #[test]
353 fn test_resource_collection_to_array() {
354 let products = vec![
355 Product {
356 sku: "P1".into(),
357 price: 10.0,
358 internal_note: "x".into(),
359 },
360 Product {
361 sku: "P2".into(),
362 price: 20.0,
363 internal_note: "y".into(),
364 },
365 ];
366 let collection = ProductResource::collection(products);
367 let arr = collection.to_array();
368 assert!(arr.get("data").is_some());
369 assert!(arr.get("meta").is_some());
370 let data = arr["data"].as_array().unwrap();
371 assert_eq!(data.len(), 2);
372 assert_eq!(arr["meta"]["count"].as_u64(), Some(2));
373 }
374
375 #[test]
376 fn test_resource_collection_with_extra_meta() {
377 let products = vec![Product {
378 sku: "P1".into(),
379 price: 10.0,
380 internal_note: "x".into(),
381 }];
382 let mut extra = HashMap::new();
383 extra.insert("page".to_string(), json!(1));
384 extra.insert("total".to_string(), json!(100));
385
386 let arr = ProductResource::collection(products).with_meta(extra);
387 assert_eq!(arr["meta"]["page"].as_u64(), Some(1));
388 assert_eq!(arr["meta"]["total"].as_u64(), Some(100));
389 assert_eq!(arr["meta"]["count"].as_u64(), Some(1));
390 }
391
392 #[test]
393 fn test_json_resource_into_inner() {
394 let product = Product {
395 sku: "INNER".into(),
396 price: 5.0,
397 internal_note: "note".into(),
398 };
399 let resource = ProductResource::make(product);
400 let inner = resource.into_inner();
401 assert_eq!(inner.sku, "INNER");
402 }
403
404 #[test]
405 fn test_resource_collection_into_inner() {
406 let products = vec![Product {
407 sku: "C1".into(),
408 price: 1.0,
409 internal_note: "n".into(),
410 }];
411 let collection = ProductResource::collection(products);
412 let inner = collection.into_inner();
413 assert_eq!(inner.len(), 1);
414 assert_eq!(inner[0].sku, "C1");
415 }
416
417 use larastvel_macros::api_resource;
422
423 #[api_resource(Product)]
424 struct ProductApiResource;
425
426 impl ProductApiResource {
427 fn to_array(model: &Product) -> Value {
428 json!({ "sku": model.sku, "price": model.price })
429 }
430 }
431
432 #[test]
433 fn test_api_resource_macro_transform() {
434 let product = Product {
435 sku: "TEST-1".into(),
436 price: 15.0,
437 internal_note: "hidden".into(),
438 };
439 let arr = <ProductApiResource as ApiResource<Product>>::transform(&product);
440 assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("TEST-1"));
441 assert_eq!(arr.get("price").and_then(|v| v.as_f64()), Some(15.0));
442 assert!(arr.get("internal_note").is_none());
443 }
444
445 #[test]
446 fn test_api_resource_macro_make() {
447 let product = Product {
448 sku: "MAKE-1".into(),
449 price: 25.0,
450 internal_note: "x".into(),
451 };
452 let resource = ProductApiResource::make(product);
453 let arr = resource.to_array();
454 assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("MAKE-1"));
455 }
456
457 #[test]
458 fn test_api_resource_macro_collection() {
459 let products = vec![
460 Product {
461 sku: "A".into(),
462 price: 1.0,
463 internal_note: "x".into(),
464 },
465 Product {
466 sku: "B".into(),
467 price: 2.0,
468 internal_note: "y".into(),
469 },
470 ];
471 let collection = ProductApiResource::collection(products);
472 let arr = collection.to_array();
473 assert!(arr.get("data").is_some());
474 assert_eq!(arr["data"].as_array().unwrap().len(), 2);
475 }
476
477 #[api_resource(self::Product)]
479 struct SubResource;
480
481 impl SubResource {
482 fn to_array(model: &Product) -> Value {
483 json!({ "sku": model.sku })
484 }
485 }
486
487 #[test]
488 fn test_api_resource_macro_module_path() {
489 let product = Product {
490 sku: "MOD-1".into(),
491 price: 0.0,
492 internal_note: "".into(),
493 };
494 let arr = <SubResource as ApiResource<Product>>::transform(&product);
495 assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("MOD-1"));
496 }
497}