larastvel-core 0.2.2

Larastvel framework core - inspired by Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::collections::HashMap;

use serde::Serialize;
use serde_json::{json, Value};

/// Trait for model serialization — Laravel's `toArray()` / `toJson()` pattern.
///
/// Models that implement this trait get automatic conversion to JSON with
/// support for:
/// - `hidden()` — fields to exclude from output (like `$hidden`)
/// - `appends()` — computed attributes to include (like `$appends`)
/// - `get_appended()` — compute values for appended attributes
///
/// # Example
///
/// ```rust,ignore
/// impl SerializesToArray for User {
///     fn hidden() -> Vec<&'static str> { vec!["password"] }
///     fn appends() -> Vec<&'static str> { vec!["full_name"] }
///     fn get_appended(&self, key: &str) -> Option<Value> {
///         match key {
///             "full_name" => Some(json!(format!("{} {}", self.first_name, self.last_name))),
///             _ => None,
///         }
///     }
/// }
/// ```
pub trait SerializesToArray: Send + Sync + Serialize {
    /// Fields to exclude from serialization output (like `$hidden`).
    fn hidden() -> Vec<&'static str>
    where
        Self: Sized,
    {
        vec![]
    }

    /// Computed attributes to append to serialization output (like `$appends`).
    fn appends() -> Vec<&'static str>
    where
        Self: Sized,
    {
        vec![]
    }

    /// Return the value for a computed attribute.
    ///
    /// Only called for keys returned by `appends()`.
    fn get_appended(&self, _key: &str) -> Option<Value> {
        None
    }

    /// Convert the model to a JSON [`Value`], respecting `hidden` / `appends`.
    fn to_array(&self) -> Value
    where
        Self: Sized,
    {
        let mut value = serde_json::to_value(self).unwrap_or(Value::Null);
        if let Value::Object(ref mut map) = value {
            for key in Self::hidden() {
                map.remove(key);
            }
            for key in Self::appends() {
                if let Some(val) = self.get_appended(key) {
                    map.insert(key.to_string(), val);
                }
            }
        }
        value
    }

    /// Convert the model to a pretty-printed JSON string.
    fn to_json(&self) -> Result<String, serde_json::Error>
    where
        Self: Sized,
    {
        serde_json::to_string_pretty(&self.to_array())
    }

    /// Convert the model to a compact JSON string.
    fn to_json_compact(&self) -> Result<String, serde_json::Error>
    where
        Self: Sized,
    {
        serde_json::to_string(&self.to_array())
    }
}

// ---------------------------------------------------------------------------
// API Resources — JsonResource & ResourceCollection
// ---------------------------------------------------------------------------

/// A trait that lets you customise how a model is transformed for API output.
///
/// This is the Rust equivalent of Laravel's `JsonResource::toArray($request)`.
///
/// # Example
///
/// ```rust,ignore
/// struct UserResource;
///
/// impl ApiResource<User> for UserResource {
///     fn transform(model: &User) -> Value {
///         json!({
///             "id": model.id,
///             "email": model.email,
///         })
///     }
/// }
/// ```
pub trait ApiResource<T: Serialize + Send + Sync + 'static>: Sized {
    /// Transform a single model into the API representation.
    fn transform(model: &T) -> Value;

    /// Create a `JsonResource` wrapping the given model.
    fn make(model: T) -> JsonResource<T, Self> {
        JsonResource {
            inner: model,
            _marker: std::marker::PhantomData,
        }
    }

    /// Create a `ResourceCollection` wrapping the given models.
    fn collection(models: Vec<T>) -> ResourceCollection<T, Self> {
        ResourceCollection {
            inner: models,
            _marker: std::marker::PhantomData,
        }
    }
}

/// A single model wrapped for API output.
///
/// Use together with an [`ApiResource`] implementor.
pub struct JsonResource<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> {
    inner: T,
    _marker: std::marker::PhantomData<R>,
}

impl<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> JsonResource<T, R> {
    /// Return the API representation as a JSON [`Value`].
    pub fn to_array(&self) -> Value {
        R::transform(&self.inner)
    }

    /// Return the API representation as a pretty-printed JSON string.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_array())
    }

    /// Consume the resource and return the inner model.
    pub fn into_inner(self) -> T {
        self.inner
    }
}

/// A collection of models wrapped for API output.
///
/// Laravel-compatible JSON structure:
/// ```json
/// { "data": [...], "meta": { "count": ... } }
/// ```
pub struct ResourceCollection<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> {
    inner: Vec<T>,
    _marker: std::marker::PhantomData<R>,
}

impl<T: Serialize + Send + Sync + 'static, R: ApiResource<T>> ResourceCollection<T, R> {
    /// Return the API representation as a JSON [`Value`].
    ///
    /// Includes `data` and `meta` (count) keys.
    pub fn to_array(&self) -> Value {
        let data: Vec<Value> = self.inner.iter().map(|item| R::transform(item)).collect();
        json!({
            "data": data,
            "meta": {
                "count": self.inner.len(),
            }
        })
    }

    /// Return the API representation as a pretty-printed JSON string.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_array())
    }

    /// Add additional meta keys to the response.
    pub fn with_meta(self, extra: HashMap<String, Value>) -> Value {
        let mut base = self.to_array();
        if let Value::Object(ref mut map) = base {
            if let Some(Value::Object(ref mut meta)) = map.get_mut("meta") {
                for (k, v) in extra {
                    meta.insert(k, v);
                }
            }
        }
        base
    }

    /// Consume the collection and return the inner models.
    pub fn into_inner(self) -> Vec<T> {
        self.inner
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    use serde::Serialize;

    #[derive(Debug, Clone, Serialize)]
    struct User {
        id: u64,
        name: String,
        email: String,
        password: String,
    }

    impl SerializesToArray for User {
        fn hidden() -> Vec<&'static str> {
            vec!["password"]
        }

        fn appends() -> Vec<&'static str> {
            vec!["greeting"]
        }

        fn get_appended(&self, key: &str) -> Option<Value> {
            match key {
                "greeting" => Some(json!("Hello, ".to_string() + &self.name)),
                _ => None,
            }
        }
    }

    #[test]
    fn test_to_array_hides_fields() {
        let user = User {
            id: 1,
            name: "Alice".into(),
            email: "alice@test.com".into(),
            password: "secret".into(),
        };
        let arr = user.to_array();
        assert!(arr.get("password").is_none());
        assert_eq!(arr.get("id").and_then(|v| v.as_u64()), Some(1));
        assert_eq!(arr.get("name").and_then(|v| v.as_str()), Some("Alice"));
    }

    #[test]
    fn test_to_array_appends_fields() {
        let user = User {
            id: 2,
            name: "Bob".into(),
            email: "bob@test.com".into(),
            password: "hunter2".into(),
        };
        let arr = user.to_array();
        assert_eq!(
            arr.get("greeting").and_then(|v| v.as_str()),
            Some("Hello, Bob")
        );
    }

    #[test]
    fn test_to_json_roundtrip() {
        let user = User {
            id: 3,
            name: "Charlie".into(),
            email: "charlie@test.com".into(),
            password: "p4ss".into(),
        };
        let json_str = user.to_json().unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed.get("id").and_then(|v| v.as_u64()), Some(3));
        assert!(parsed.get("password").is_none());
    }

    #[test]
    fn test_to_json_compact_no_newlines() {
        let user = User {
            id: 1,
            name: "Diana".into(),
            email: "diana@test.com".into(),
            password: "x".into(),
        };
        let compact = user.to_json_compact().unwrap();
        assert!(!compact.contains('\n'));
        assert!(compact.contains("Diana"));
    }

    #[test]
    fn test_default_hidden_and_appends() {
        #[derive(Debug, Clone, Serialize)]
        struct Simple {
            id: u64,
            label: String,
        }

        impl SerializesToArray for Simple {}

        let s = Simple {
            id: 10,
            label: "test".into(),
        };
        let arr = s.to_array();
        assert_eq!(arr.get("id").and_then(|v| v.as_u64()), Some(10));
        assert_eq!(arr.get("label").and_then(|v| v.as_str()), Some("test"));
    }

    // -----------------------------------------------------------------------
    // API Resource tests
    // -----------------------------------------------------------------------

    #[derive(Debug, Clone, Serialize)]
    struct Product {
        sku: String,
        price: f64,
        internal_note: String,
    }

    struct ProductResource;

    impl ApiResource<Product> for ProductResource {
        fn transform(model: &Product) -> Value {
            json!({
                "sku": model.sku,
                "price": model.price,
            })
        }
    }

    #[test]
    fn test_json_resource_to_array() {
        let product = Product {
            sku: "ABC-123".into(),
            price: 29.99,
            internal_note: "ignore me".into(),
        };
        let resource = ProductResource::make(product);
        let arr = resource.to_array();
        assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("ABC-123"));
        assert_eq!(arr.get("price").and_then(|v| v.as_f64()), Some(29.99));
        assert!(arr.get("internal_note").is_none());
    }

    #[test]
    fn test_resource_collection_to_array() {
        let products = vec![
            Product {
                sku: "P1".into(),
                price: 10.0,
                internal_note: "x".into(),
            },
            Product {
                sku: "P2".into(),
                price: 20.0,
                internal_note: "y".into(),
            },
        ];
        let collection = ProductResource::collection(products);
        let arr = collection.to_array();
        assert!(arr.get("data").is_some());
        assert!(arr.get("meta").is_some());
        let data = arr["data"].as_array().unwrap();
        assert_eq!(data.len(), 2);
        assert_eq!(arr["meta"]["count"].as_u64(), Some(2));
    }

    #[test]
    fn test_resource_collection_with_extra_meta() {
        let products = vec![Product {
            sku: "P1".into(),
            price: 10.0,
            internal_note: "x".into(),
        }];
        let mut extra = HashMap::new();
        extra.insert("page".to_string(), json!(1));
        extra.insert("total".to_string(), json!(100));

        let arr = ProductResource::collection(products).with_meta(extra);
        assert_eq!(arr["meta"]["page"].as_u64(), Some(1));
        assert_eq!(arr["meta"]["total"].as_u64(), Some(100));
        assert_eq!(arr["meta"]["count"].as_u64(), Some(1));
    }

    #[test]
    fn test_json_resource_into_inner() {
        let product = Product {
            sku: "INNER".into(),
            price: 5.0,
            internal_note: "note".into(),
        };
        let resource = ProductResource::make(product);
        let inner = resource.into_inner();
        assert_eq!(inner.sku, "INNER");
    }

    #[test]
    fn test_resource_collection_into_inner() {
        let products = vec![Product {
            sku: "C1".into(),
            price: 1.0,
            internal_note: "n".into(),
        }];
        let collection = ProductResource::collection(products);
        let inner = collection.into_inner();
        assert_eq!(inner.len(), 1);
        assert_eq!(inner[0].sku, "C1");
    }

    // -----------------------------------------------------------------------
    // #[api_resource] macro tests
    // -----------------------------------------------------------------------

    use larastvel_macros::api_resource;

    #[api_resource(Product)]
    struct ProductApiResource;

    impl ProductApiResource {
        fn to_array(model: &Product) -> Value {
            json!({ "sku": model.sku, "price": model.price })
        }
    }

    #[test]
    fn test_api_resource_macro_transform() {
        let product = Product {
            sku: "TEST-1".into(),
            price: 15.0,
            internal_note: "hidden".into(),
        };
        let arr = <ProductApiResource as ApiResource<Product>>::transform(&product);
        assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("TEST-1"));
        assert_eq!(arr.get("price").and_then(|v| v.as_f64()), Some(15.0));
        assert!(arr.get("internal_note").is_none());
    }

    #[test]
    fn test_api_resource_macro_make() {
        let product = Product {
            sku: "MAKE-1".into(),
            price: 25.0,
            internal_note: "x".into(),
        };
        let resource = ProductApiResource::make(product);
        let arr = resource.to_array();
        assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("MAKE-1"));
    }

    #[test]
    fn test_api_resource_macro_collection() {
        let products = vec![
            Product {
                sku: "A".into(),
                price: 1.0,
                internal_note: "x".into(),
            },
            Product {
                sku: "B".into(),
                price: 2.0,
                internal_note: "y".into(),
            },
        ];
        let collection = ProductApiResource::collection(products);
        let arr = collection.to_array();
        assert!(arr.get("data").is_some());
        assert_eq!(arr["data"].as_array().unwrap().len(), 2);
    }

    /// Resource with a module path argument
    #[api_resource(self::Product)]
    struct SubResource;

    impl SubResource {
        fn to_array(model: &Product) -> Value {
            json!({ "sku": model.sku })
        }
    }

    #[test]
    fn test_api_resource_macro_module_path() {
        let product = Product {
            sku: "MOD-1".into(),
            price: 0.0,
            internal_note: "".into(),
        };
        let arr = <SubResource as ApiResource<Product>>::transform(&product);
        assert_eq!(arr.get("sku").and_then(|v| v.as_str()), Some("MOD-1"));
    }
}