reinhardt-rest 0.1.0

REST API framework aggregator for Reinhardt
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! QuerySet integration for serializers
//!
//! This module provides integration between serializers and the ORM's QuerySet,
//! enabling seamless saving of validated data to the database.
//!
//! # Features
//!
//! - `SerializerSaveMixin` trait for database operations
//! - Pre-save validation hooks
//! - Error propagation from validators to save operations
//! - Transaction support for atomic operations

use super::SerializerError;
use async_trait::async_trait;
use reinhardt_db::orm::{Model, QuerySet};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
use std::collections::HashMap;

/// Mixin trait for serializers that can save to database via QuerySet
///
/// This trait provides Django REST Framework-style `save()` and `create()` methods
/// that integrate with the ORM's QuerySet.
///
/// # Examples
///
/// ```rust,no_run,ignore
/// # #[tokio::main]
/// # async fn main() {
/// use reinhardt_rest::serializers::{Serializer, SerializerSaveMixin};
///
/// #[derive(Serialize, Deserialize)]
/// struct User {
///     id: Option<i64>,
///     username: String,
///     email: String,
/// }
///
/// impl Model for User {
///     type PrimaryKey = i64;
///     fn table_name() -> &'static str { "users" }
///     // ... other implementations
/// }
///
/// struct UserSerializer;
///
/// impl Serializer for UserSerializer {
///     type Model = User;
///     // ... serializer implementation
/// }
///
/// impl SerializerSaveMixin for UserSerializer {}
///
/// // Usage
/// let data = json!({"username": "alice", "email": "alice@example.com"});
/// // Verify create operation succeeds (requires database)
/// let user = UserSerializer::create(data).await?;
///
/// # }
/// ```
#[async_trait]
pub trait SerializerSaveMixin
where
	Self: Sized,
{
	/// The model type this serializer works with
	type Model: Model + Serialize + DeserializeOwned + Clone + Send + Sync;

	/// Create a new instance in the database
	///
	/// This method:
	/// 1. Validates the input data
	/// 2. Deserializes to model instance
	/// 3. Saves to database via QuerySet.create()
	/// 4. Returns the created instance
	///
	/// # Errors
	///
	/// Returns `SerializerError` if:
	/// - Validation fails
	/// - Deserialization fails
	/// - Database operation fails
	///
	/// # Examples
	///
	/// ```ignore
	/// let data = json!({
	///     "username": "alice",
	///     "email": "alice@example.com"
	/// });
	///
	/// // Verify user creation succeeds (requires database)
	/// let user = UserSerializer::create(data).await?;
	/// assert_eq!(user.username, "alice");
	/// ```
	async fn create(data: Value) -> Result<Self::Model, SerializerError> {
		// Pre-save validation
		Self::validate_for_create(&data).await?;

		// Deserialize to model
		let model: Self::Model =
			serde_json::from_value(data).map_err(|e| SerializerError::Serde {
				message: format!("Failed to deserialize: {}", e),
			})?;

		// Save to database
		let queryset = QuerySet::<Self::Model>::new();
		let created = queryset
			.create(model)
			.await
			.map_err(|e| SerializerError::Other {
				message: format!("Failed to create: {}", e),
			})?;
		Ok(created)
	}

	/// Update an existing instance in the database
	///
	/// This method:
	/// 1. Validates the input data
	/// 2. Merges with existing instance
	/// 3. Saves to database
	/// 4. Returns the updated instance
	///
	/// # Errors
	///
	/// Returns `SerializerError` if:
	/// - Validation fails
	/// - Instance not found
	/// - Database operation fails
	///
	/// # Examples
	///
	/// ```ignore
	/// let data = json!({"email": "newemail@example.com"});
	/// // Verify update operation merges data correctly (requires database)
	/// let updated = UserSerializer::update(user, data).await?;
	/// assert_eq!(updated.email, "newemail@example.com");
	/// ```
	async fn update(
		mut instance: Self::Model,
		data: Value,
	) -> Result<Self::Model, SerializerError> {
		// Pre-save validation with instance
		Self::validate_for_update(&data, Some(&instance)).await?;

		// Merge data into instance
		if let Value::Object(map) = data {
			let instance_value =
				serde_json::to_value(&instance).map_err(|e| SerializerError::Serde {
					message: format!("Failed to serialize instance: {}", e),
				})?;

			if let Value::Object(mut instance_map) = instance_value {
				for (key, value) in map {
					instance_map.insert(key, value);
				}

				instance = serde_json::from_value(Value::Object(instance_map)).map_err(|e| {
					SerializerError::Serde {
						message: format!("Failed to deserialize updated instance: {}", e),
					}
				})?;
			}
		}

		// Integrate with Manager.update()
		use reinhardt_db::orm::manager::Manager;

		let manager = Manager::<Self::Model>::new();
		let updated = manager
			.update(&instance)
			.await
			.map_err(|e| SerializerError::Other {
				message: format!("Failed to update instance: {}", e),
			})?;

		Ok(updated)
	}

	/// Save the instance to database (create or update)
	///
	/// This method automatically determines whether to create or update
	/// based on whether the instance has a primary key.
	///
	/// # Examples
	///
	/// ```ignore
	/// // Create new instance
	/// let data = json!({"username": "alice", "email": "alice@example.com"});
	/// // Verify save creates new instance (requires database)
	/// let user = UserSerializer::save(data, None).await?;
	///
	/// // Update existing instance
	/// let update_data = json!({"email": "newemail@example.com"});
	/// // Verify save updates existing instance (requires database)
	/// let updated = UserSerializer::save(update_data, Some(user)).await?;
	/// ```
	async fn save(
		data: Value,
		instance: Option<Self::Model>,
	) -> Result<Self::Model, SerializerError> {
		match instance {
			Some(inst) => Self::update(inst, data).await,
			None => Self::create(data).await,
		}
	}

	/// Pre-save validation hook for create operations
	///
	/// Override this method to add custom validation logic that runs
	/// before creating a new instance.
	///
	/// # Examples
	///
	/// ```ignore
	/// impl SerializerSaveMixin for UserSerializer {
	///     async fn validate_for_create(data: &Value) -> Result<(), SerializerError> {
	///         // Custom validation
	///         if let Some(username) = data.get("username") {
	///             // Verify username length validation
	///             if username.as_str().unwrap().len() < 3 {
	///                 return Err(SerializerError::validation(
	///                     ValidatorError::FieldValidation {
	///                         field_name: "username".to_string(),
	///                         value: username.to_string(),
	///                         constraint: "min_length=3".to_string(),
	///                         message: "Username too short".to_string(),
	///                     }
	///                 ));
	///             }
	///         }
	///         Ok(())
	///     }
	/// }
	/// ```
	async fn validate_for_create(_data: &Value) -> Result<(), SerializerError> {
		Ok(())
	}

	/// Pre-save validation hook for update operations
	///
	/// Override this method to add custom validation logic that runs
	/// before updating an existing instance.
	///
	/// # Examples
	///
	/// ```ignore
	/// impl SerializerSaveMixin for UserSerializer {
	///     async fn validate_for_update(
	///         data: &Value,
	///         instance: Option<&User>,
	///     ) -> Result<(), SerializerError> {
	///         // Custom validation with access to existing instance
	///         if let Some(user) = instance {
	///             // Verify admin role protection
	///             if user.is_admin && data.get("role").is_some() {
	///                 return Err(SerializerError::validation(
	///                     ValidatorError::Custom {
	///                         message: "Cannot change admin role".to_string(),
	///                     }
	///                 ));
	///             }
	///         }
	///         Ok(())
	///     }
	/// }
	/// ```
	async fn validate_for_update(
		_data: &Value,
		_instance: Option<&Self::Model>,
	) -> Result<(), SerializerError> {
		Ok(())
	}
}

/// Context for serializer save operations
///
/// Provides access to additional context needed during save operations.
#[derive(Debug, Clone, Default)]
pub struct SaveContext {
	/// Additional context data
	pub extra: HashMap<String, Value>,
}

impl SaveContext {
	/// Create a new save context
	pub fn new() -> Self {
		Self {
			extra: HashMap::new(),
		}
	}

	/// Add extra context data
	pub fn with_extra(mut self, key: String, value: Value) -> Self {
		self.extra.insert(key, value);
		self
	}
}

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

	#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
	struct TestUser {
		id: Option<i64>,
		username: String,
		email: String,
	}

	#[derive(Debug, Clone)]
	struct TestUserFields;

	impl FieldSelector for TestUserFields {
		fn with_alias(self, _alias: &str) -> Self {
			self
		}
	}

	impl Model for TestUser {
		type PrimaryKey = i64;
		type Fields = TestUserFields;

		fn table_name() -> &'static str {
			"test_users"
		}

		fn new_fields() -> Self::Fields {
			TestUserFields
		}

		fn primary_key(&self) -> Option<Self::PrimaryKey> {
			self.id
		}

		fn set_primary_key(&mut self, value: Self::PrimaryKey) {
			self.id = Some(value);
		}
	}

	struct TestUserSerializer;

	impl SerializerSaveMixin for TestUserSerializer {
		type Model = TestUser;
	}

	#[test]
	fn test_save_context_creation() {
		let context = SaveContext::new();
		assert!(context.extra.is_empty());
	}

	#[test]
	fn test_save_context_with_extra() {
		let context = SaveContext::new()
			.with_extra("key1".to_string(), serde_json::json!("value1"))
			.with_extra("key2".to_string(), serde_json::json!(42));

		assert_eq!(context.extra.len(), 2);
		assert_eq!(
			context.extra.get("key1").unwrap(),
			&serde_json::json!("value1")
		);
		assert_eq!(context.extra.get("key2").unwrap(), &serde_json::json!(42));
	}

	#[tokio::test]
	async fn test_validate_for_create_default() {
		let data = serde_json::json!({
			"username": "testuser",
			"email": "test@example.com"
		});

		let result = TestUserSerializer::validate_for_create(&data).await;
		assert!(result.is_ok());
	}

	#[tokio::test]
	async fn test_validate_for_update_default() {
		let data = serde_json::json!({"email": "newemail@example.com"});
		let instance = TestUser {
			id: Some(1),
			username: "testuser".to_string(),
			email: "old@example.com".to_string(),
		};

		let result = TestUserSerializer::validate_for_update(&data, Some(&instance)).await;
		assert!(result.is_ok());
	}

	// Note: Integration tests with actual database would go in tests/ directory
}

/// Cache-aware save context
///
/// Extends SaveContext with automatic cache invalidation support.
///
/// # Examples
///
/// ```
/// use reinhardt_rest::serializers::queryset_integration::CacheAwareSaveContext;
/// use reinhardt_rest::serializers::{CacheInvalidator, InvalidationStrategy};
///
/// let invalidator = CacheInvalidator::new(InvalidationStrategy::Immediate);
/// let context = CacheAwareSaveContext::with_invalidator(invalidator);
///
/// // Verify context is created with invalidator
/// let _: CacheAwareSaveContext = context;
/// ```
#[derive(Debug, Clone)]
pub struct CacheAwareSaveContext {
	/// Base save context
	pub context: SaveContext,
	/// Cache invalidator (optional)
	pub invalidator: Option<crate::serializers::CacheInvalidator>,
}

impl CacheAwareSaveContext {
	/// Create a new cache-aware context without invalidator
	pub fn new() -> Self {
		Self {
			context: SaveContext::new(),
			invalidator: None,
		}
	}

	/// Create a cache-aware context with invalidator
	pub fn with_invalidator(invalidator: crate::serializers::CacheInvalidator) -> Self {
		Self {
			context: SaveContext::new(),
			invalidator: Some(invalidator),
		}
	}

	/// Invalidate cache for a model instance
	///
	/// Call this after successful save/update operations.
	pub fn invalidate_cache(&self, model_name: &str, pk: &str) -> Vec<String> {
		if let Some(ref invalidator) = self.invalidator {
			invalidator.invalidate(model_name, pk)
		} else {
			Vec::new()
		}
	}

	/// Add cache dependency before save
	///
	/// Register that a cache key depends on this model instance.
	pub fn add_cache_dependency(&self, cache_key: &str, model_name: &str, pk: &str) {
		if let Some(ref invalidator) = self.invalidator {
			invalidator.add_dependency(cache_key, model_name, pk);
		}
	}

	/// Get the underlying SaveContext
	pub fn inner(&self) -> &SaveContext {
		&self.context
	}

	/// Convert to SaveContext
	pub fn into_inner(self) -> SaveContext {
		self.context
	}
}

impl Default for CacheAwareSaveContext {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod cache_aware_tests {
	use super::*;
	use crate::serializers::InvalidationStrategy;

	#[test]
	fn test_cache_aware_save_context_without_invalidator() {
		let context = CacheAwareSaveContext::new();
		assert!(context.invalidator.is_none());

		// Should not panic, just return empty vec
		let keys = context.invalidate_cache("User", "123");
		assert_eq!(keys.len(), 0);
	}

	#[test]
	fn test_cache_aware_save_context_with_invalidator() {
		let invalidator =
			crate::serializers::CacheInvalidator::new(InvalidationStrategy::Immediate);
		let context = CacheAwareSaveContext::with_invalidator(invalidator);

		assert!(context.invalidator.is_some());

		// Add dependency
		context.add_cache_dependency("user:123:profile", "User", "123");

		// Invalidate
		let keys = context.invalidate_cache("User", "123");
		assert_eq!(keys.len(), 1);
		assert_eq!(keys[0], "user:123:profile");
	}

	#[test]
	fn test_cache_aware_save_context_inner() {
		let context = CacheAwareSaveContext::new();
		let inner = context.inner();
		assert!(inner.extra.is_empty());
	}

	#[test]
	fn test_cache_aware_save_context_into_inner() {
		let context = CacheAwareSaveContext::new();
		let inner = context.into_inner();
		assert!(inner.extra.is_empty());
	}
}