this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
//! Entity traits defining the core abstraction for all data types

use anyhow::Result;
use chrono::{DateTime, Utc};
use std::sync::Arc;
use uuid::Uuid;

/// Base trait for all entities in the system.
///
/// This trait provides the fundamental metadata needed for any entity type.
/// All entities have:
/// - id: Unique identifier
/// - type: Entity type name (e.g., "user", "product")
/// - created_at: Creation timestamp
/// - updated_at: Last modification timestamp
/// - deleted_at: Soft deletion timestamp (optional)
/// - status: Current status of the entity
pub trait Entity: Clone + Send + Sync + 'static {
    /// The service type that handles operations for this entity
    type Service: Send + Sync;

    /// The plural resource name used in URLs (e.g., "users", "companies")
    fn resource_name() -> &'static str;

    /// The singular resource name (e.g., "user", "company")
    fn resource_name_singular() -> &'static str;

    /// Extract the service instance from the application host/state
    fn service_from_host(host: &Arc<dyn std::any::Any + Send + Sync>)
    -> Result<Arc<Self::Service>>;

    // === Core Entity Fields ===

    /// Get the unique identifier for this entity instance
    fn id(&self) -> Uuid;

    /// Get the entity type name
    fn entity_type(&self) -> &str;

    /// Get the creation timestamp
    fn created_at(&self) -> DateTime<Utc>;

    /// Get the last update timestamp
    fn updated_at(&self) -> DateTime<Utc>;

    /// Get the deletion timestamp (soft delete)
    fn deleted_at(&self) -> Option<DateTime<Utc>>;

    /// Get the entity status
    fn status(&self) -> &str;

    // === Utility Methods ===

    /// Get the tenant ID for multi-tenant isolation.
    ///
    /// Returns None by default for single-tenant applications or system-wide entities.
    /// Override this method to enable multi-tenancy for specific entity types.
    ///
    /// # Multi-Tenant Usage
    ///
    /// ```rust,ignore
    /// impl Entity for MyEntity {
    ///     fn tenant_id(&self) -> Option<Uuid> {
    ///         self.tenant_id  // Return actual tenant_id field
    ///     }
    /// }
    /// ```
    fn tenant_id(&self) -> Option<Uuid> {
        None
    }

    /// Check if the entity has been soft-deleted
    fn is_deleted(&self) -> bool {
        self.deleted_at().is_some()
    }

    /// Check if the entity is active (status == "active" and not deleted)
    fn is_active(&self) -> bool {
        self.status() == "active" && !self.is_deleted()
    }
}

/// Trait for data entities that represent concrete domain objects.
///
/// Data entities extend the base Entity with:
/// - name: A human-readable name
/// - indexed_fields: Fields that can be searched
/// - field_value: Dynamic field access
pub trait Data: Entity {
    /// Get the name of this data entity
    fn name(&self) -> &str;

    /// List of fields that should be indexed for searching
    fn indexed_fields() -> &'static [&'static str];

    /// Get the value of a specific field by name
    fn field_value(&self, field: &str) -> Option<crate::core::field::FieldValue>;

    /// Display the entity for debugging
    fn display(&self) {
        println!(
            "[{}] {} - {} ({})",
            self.id(),
            self.entity_type(),
            self.name(),
            self.status()
        );
    }
}

/// Trait for link entities that represent relationships between entities.
///
/// Links extend the base Entity with:
/// - source_id: The ID of the source entity
/// - target_id: The ID of the target entity
/// - link_type: The type of relationship
pub trait Link: Entity {
    /// Get the source entity ID
    fn source_id(&self) -> Uuid;

    /// Get the target entity ID
    fn target_id(&self) -> Uuid;

    /// Get the link type (e.g., "owner", "worker")
    fn link_type(&self) -> &str;

    /// Display the link for debugging
    fn display(&self) {
        println!(
            "[{}] {} → {} (type: {}, status: {})",
            self.id(),
            self.source_id(),
            self.target_id(),
            self.link_type(),
            self.status()
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    // Example entity for testing trait definitions
    #[derive(Clone, Debug, Serialize, Deserialize)]
    struct TestEntity {
        id: Uuid,
        entity_type: String,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
        deleted_at: Option<DateTime<Utc>>,
        status: String,
    }

    impl Entity for TestEntity {
        type Service = ();

        fn resource_name() -> &'static str {
            "test_entities"
        }

        fn resource_name_singular() -> &'static str {
            "test_entity"
        }

        fn service_from_host(
            _host: &Arc<dyn std::any::Any + Send + Sync>,
        ) -> Result<Arc<Self::Service>> {
            Ok(Arc::new(()))
        }

        fn id(&self) -> Uuid {
            self.id
        }

        fn entity_type(&self) -> &str {
            &self.entity_type
        }

        fn created_at(&self) -> DateTime<Utc> {
            self.created_at
        }

        fn updated_at(&self) -> DateTime<Utc> {
            self.updated_at
        }

        fn deleted_at(&self) -> Option<DateTime<Utc>> {
            self.deleted_at
        }

        fn status(&self) -> &str {
            &self.status
        }
    }

    #[test]
    fn test_entity_is_deleted() {
        let now = Utc::now();
        let mut entity = TestEntity {
            id: Uuid::new_v4(),
            entity_type: "test".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "active".to_string(),
        };

        assert!(!entity.is_deleted());
        assert!(entity.is_active());

        entity.deleted_at = Some(now);
        assert!(entity.is_deleted());
        assert!(!entity.is_active());
    }

    #[test]
    fn test_entity_metadata() {
        assert_eq!(TestEntity::resource_name(), "test_entities");
        assert_eq!(TestEntity::resource_name_singular(), "test_entity");
    }

    #[test]
    fn test_entity_default_tenant_id_is_none() {
        let now = Utc::now();
        let entity = TestEntity {
            id: Uuid::new_v4(),
            entity_type: "test".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "active".to_string(),
        };
        assert_eq!(entity.tenant_id(), None);
    }

    #[test]
    fn test_entity_is_active_with_inactive_status() {
        let now = Utc::now();
        let entity = TestEntity {
            id: Uuid::new_v4(),
            entity_type: "test".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "inactive".to_string(),
        };
        assert!(!entity.is_active());
        assert!(!entity.is_deleted());
    }

    #[test]
    fn test_entity_service_from_host() {
        let host: Arc<dyn std::any::Any + Send + Sync> = Arc::new(());
        let svc = TestEntity::service_from_host(&host).expect("service_from_host should succeed");
        // We just verify it returns successfully; the service is ()
        assert_eq!(*svc, ());
    }

    // --- Link trait ---

    #[derive(Clone, Debug)]
    struct TestLink {
        id: Uuid,
        source_id: Uuid,
        target_id: Uuid,
        link_type: String,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
        deleted_at: Option<DateTime<Utc>>,
        status: String,
    }

    impl Entity for TestLink {
        type Service = ();

        fn resource_name() -> &'static str {
            "test_links"
        }

        fn resource_name_singular() -> &'static str {
            "test_link"
        }

        fn service_from_host(
            _host: &Arc<dyn std::any::Any + Send + Sync>,
        ) -> Result<Arc<Self::Service>> {
            Ok(Arc::new(()))
        }

        fn id(&self) -> Uuid {
            self.id
        }

        fn entity_type(&self) -> &str {
            "test_link"
        }

        fn created_at(&self) -> DateTime<Utc> {
            self.created_at
        }

        fn updated_at(&self) -> DateTime<Utc> {
            self.updated_at
        }

        fn deleted_at(&self) -> Option<DateTime<Utc>> {
            self.deleted_at
        }

        fn status(&self) -> &str {
            &self.status
        }
    }

    impl Link for TestLink {
        fn source_id(&self) -> Uuid {
            self.source_id
        }

        fn target_id(&self) -> Uuid {
            self.target_id
        }

        fn link_type(&self) -> &str {
            &self.link_type
        }
    }

    #[test]
    fn test_link_accessors() {
        let now = Utc::now();
        let src = Uuid::new_v4();
        let tgt = Uuid::new_v4();
        let link = TestLink {
            id: Uuid::new_v4(),
            source_id: src,
            target_id: tgt,
            link_type: "ownership".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "active".to_string(),
        };
        assert_eq!(link.source_id(), src);
        assert_eq!(link.target_id(), tgt);
        assert_eq!(link.link_type(), "ownership");
    }

    #[test]
    fn test_link_is_deleted_and_is_active() {
        let now = Utc::now();
        let mut link = TestLink {
            id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            link_type: "ref".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "active".to_string(),
        };
        assert!(!link.is_deleted());
        assert!(link.is_active());

        link.deleted_at = Some(now);
        assert!(link.is_deleted());
        assert!(!link.is_active());
    }

    #[test]
    fn test_link_display_does_not_panic() {
        let now = Utc::now();
        let link = TestLink {
            id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            link_type: "ref".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "active".to_string(),
        };
        // Calling display() should not panic
        link.display();
    }

    #[test]
    fn test_link_inactive_status() {
        let now = Utc::now();
        let link = TestLink {
            id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            link_type: "ref".to_string(),
            created_at: now,
            updated_at: now,
            deleted_at: None,
            status: "suspended".to_string(),
        };
        assert!(!link.is_active());
        assert!(!link.is_deleted());
    }
}