crudcrate 0.8.0

Derive complete REST APIs from Sea-ORM entities — endpoints, filtering, pagination, batch ops, and OpenAPI on Axum
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! Error types for CRUD handlers.
//!
//! [`ApiError`] maps to HTTP status codes and implements [`IntoResponse`].
//! Internal details (database errors, stack traces) are logged via `tracing` but never
//! sent to clients.
//!
//! ```rust,ignore
//! use crudcrate::ApiError;
//!
//! async fn my_handler() -> Result<Json<MyData>, ApiError> {
//!     let data = MyEntity::find_by_id(id)
//!         .one(db)
//!         .await
//!         .map_err(ApiError::database)?
//!         .ok_or_else(|| ApiError::not_found("User", Some(id.to_string())))?;
//!     Ok(Json(data))
//! }
//! ```
//!
//! `DbErr` converts automatically: `RecordNotFound` becomes 404,
//! everything else becomes 500.

use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use sea_orm::DbErr;
use serde::{Deserialize, Serialize};
use std::fmt;
use utoipa::ToSchema;

// ============================================================================
// Batch Result Types for Partial Success
// ============================================================================

/// A single failure in a batch operation
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct BatchFailure {
    /// The index of the failed item in the original request (0-based)
    pub index: usize,
    /// The error message describing why this item failed
    pub error: String,
}

/// Result of a batch operation that may have partial success
///
/// Used when `?partial=true` is specified on batch endpoints.
/// Returns HTTP 207 Multi-Status when some items succeed and some fail.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct BatchResult<T> {
    /// Items that were successfully processed
    pub succeeded: Vec<T>,
    /// Items that failed, with their original indices and error messages
    pub failed: Vec<BatchFailure>,
}

impl<T> BatchResult<T> {
    /// Create a new empty batch result
    #[must_use]
    pub fn new() -> Self {
        Self {
            succeeded: Vec::new(),
            failed: Vec::new(),
        }
    }

    /// Add a successful item
    pub fn add_success(&mut self, item: T) {
        self.succeeded.push(item);
    }

    /// Add a failed item
    pub fn add_failure(&mut self, index: usize, error: impl Into<String>) {
        self.failed.push(BatchFailure {
            index,
            error: error.into(),
        });
    }

    /// Returns true if all items failed
    #[must_use]
    pub fn all_failed(&self) -> bool {
        self.succeeded.is_empty() && !self.failed.is_empty()
    }

    /// Returns true if all items succeeded
    #[must_use]
    pub fn all_succeeded(&self) -> bool {
        !self.succeeded.is_empty() && self.failed.is_empty()
    }

    /// Returns true if some items succeeded and some failed
    #[must_use]
    pub fn is_partial(&self) -> bool {
        !self.succeeded.is_empty() && !self.failed.is_empty()
    }
}

impl<T> Default for BatchResult<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// API error type with automatic logging and sanitized responses
///
/// This enum provides different error types that map to appropriate HTTP status codes.
/// Internal errors (like database errors) are logged but not exposed to users.
#[derive(Debug)]
pub enum ApiError {
    /// 404 Not Found - Resource doesn't exist
    NotFound {
        /// Resource type (e.g., "User", "Post")
        resource: String,
        /// Optional ID that wasn't found
        id: Option<String>,
    },

    /// 400 Bad Request - Invalid input from user
    BadRequest {
        /// User-facing error message
        message: String,
    },

    /// 401 Unauthorized - Authentication required or failed
    Unauthorized {
        /// User-facing error message
        message: String,
    },

    /// 403 Forbidden - User lacks permission
    Forbidden {
        /// User-facing error message
        message: String,
    },

    /// 409 Conflict - Resource conflict (e.g., duplicate key)
    Conflict {
        /// User-facing error message
        message: String,
    },

    /// 422 Unprocessable Entity - Validation failed
    ValidationFailed {
        /// User-facing validation errors
        errors: Vec<String>,
    },

    /// 500 Internal Server Error - Database error (details logged, not exposed)
    Database {
        /// User-facing generic message
        message: String,
        /// Internal error (logged, not sent to user)
        internal: DbErr,
    },

    /// 500 Internal Server Error - Generic internal error
    Internal {
        /// User-facing generic message
        message: String,
        /// Internal error details (logged, not sent to user)
        internal: Option<String>,
    },

    /// Custom error with specific status code
    Custom {
        /// HTTP status code
        status: StatusCode,
        /// User-facing message
        message: String,
        /// Internal error details (logged, not sent to user)
        internal: Option<String>,
    },
}

impl ApiError {
    // ============================================================================
    // Constructors for common error types
    // ============================================================================

    /// Create a 404 Not Found error
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::not_found("User", Some(user_id.to_string())));
    /// ```
    pub fn not_found(resource: impl Into<String>, id: Option<String>) -> Self {
        Self::NotFound {
            resource: resource.into(),
            id,
        }
    }

    /// Create a 400 Bad Request error
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::bad_request("Invalid email format"));
    /// ```
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::BadRequest {
            message: message.into(),
        }
    }

    /// Create a 401 Unauthorized error
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::unauthorized("Invalid credentials"));
    /// ```
    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self::Unauthorized {
            message: message.into(),
        }
    }

    /// Create a 403 Forbidden error
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::forbidden("Insufficient permissions"));
    /// ```
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::Forbidden {
            message: message.into(),
        }
    }

    /// Create a 409 Conflict error
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::conflict("Email already exists"));
    /// ```
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::Conflict {
            message: message.into(),
        }
    }

    /// Create a 422 Validation Failed error
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::validation_failed(vec![
    ///     "Email is required".to_string(),
    ///     "Password must be at least 8 characters".to_string(),
    /// ]));
    /// ```
    #[must_use]
    pub fn validation_failed(errors: Vec<String>) -> Self {
        Self::ValidationFailed { errors }
    }

    /// Create a 500 Internal Server Error from a database error
    ///
    /// The database error details are logged but NOT sent to the user.
    ///
    /// # Example
    /// ```rust,ignore
    /// let user = entity.insert(db).await.map_err(ApiError::database)?;
    /// ```
    #[must_use]
    pub fn database(err: DbErr) -> Self {
        Self::Database {
            message: "A database error occurred".to_string(),
            internal: err,
        }
    }

    /// Create a 500 Internal Server Error with optional details
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::internal("Failed to process request", Some(err.to_string())));
    /// ```
    pub fn internal(message: impl Into<String>, internal: Option<String>) -> Self {
        Self::Internal {
            message: message.into(),
            internal,
        }
    }

    /// Create a custom error with specific status code
    ///
    /// # Example
    /// ```rust,ignore
    /// return Err(ApiError::custom(
    ///     StatusCode::TOO_MANY_REQUESTS,
    ///     "Rate limit exceeded",
    ///     None
    /// ));
    /// ```
    pub fn custom(
        status: StatusCode,
        message: impl Into<String>,
        internal: Option<String>,
    ) -> Self {
        Self::Custom {
            status,
            message: message.into(),
            internal,
        }
    }

    // ============================================================================
    // Internal methods
    // ============================================================================

    /// Get the HTTP status code for this error
    fn status_code(&self) -> StatusCode {
        match self {
            Self::NotFound { .. } => StatusCode::NOT_FOUND,
            Self::BadRequest { .. } => StatusCode::BAD_REQUEST,
            Self::Unauthorized { .. } => StatusCode::UNAUTHORIZED,
            Self::Forbidden { .. } => StatusCode::FORBIDDEN,
            Self::Conflict { .. } => StatusCode::CONFLICT,
            Self::ValidationFailed { .. } => StatusCode::UNPROCESSABLE_ENTITY,
            Self::Database { .. } => StatusCode::INTERNAL_SERVER_ERROR,
            Self::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR,
            Self::Custom { status, .. } => *status,
        }
    }

    /// Get the user-facing error message (sanitized)
    fn user_message(&self) -> String {
        match self {
            Self::NotFound { resource, id } => {
                if let Some(id) = id {
                    format!("{resource} with ID '{id}' not found")
                } else {
                    format!("{resource} not found")
                }
            }
            Self::BadRequest { message } => message.clone(),
            Self::Unauthorized { message } => message.clone(),
            Self::Forbidden { message } => message.clone(),
            Self::Conflict { message } => message.clone(),
            Self::ValidationFailed { errors } => {
                if errors.len() == 1 {
                    errors[0].clone()
                } else {
                    format!("Validation failed: {}", errors.join(", "))
                }
            }
            Self::Database { message, .. } => message.clone(),
            Self::Internal { message, .. } => message.clone(),
            Self::Custom { message, .. } => message.clone(),
        }
    }

    /// Log internal error details (not sent to user)
    ///
    /// Uses the `tracing` crate - only logs if user has enabled tracing.
    /// No output if tracing is not configured.
    fn log_internal(&self) {
        match self {
            Self::Database { internal, .. } => {
                tracing::error!(
                    error = ?internal,
                    "Database error occurred"
                );
            }
            Self::Internal {
                internal: Some(details),
                ..
            } => {
                tracing::error!(
                    details = %details,
                    "Internal error occurred"
                );
            }
            Self::Custom {
                internal: Some(details),
                status,
                ..
            } => {
                tracing::error!(
                    status = %status,
                    details = %details,
                    "Custom error occurred"
                );
            }
            _ => {
                // Other errors don't have internal details to log
                // Still log at debug level for visibility
                tracing::debug!(
                    error = %self.user_message(),
                    status = %self.status_code(),
                    "API error"
                );
            }
        }
    }
}

/// Error response sent to users (sanitized)
#[derive(Serialize)]
struct ErrorResponse {
    /// Error message
    error: String,
    /// Optional list of validation errors
    #[serde(skip_serializing_if = "Option::is_none")]
    details: Option<Vec<String>>,
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        // Log internal error details (not sent to user)
        self.log_internal();

        let status = self.status_code();

        // Build sanitized response
        let response = match &self {
            Self::ValidationFailed { errors } => ErrorResponse {
                error: "Validation failed".to_string(),
                details: Some(errors.clone()),
            },
            _ => ErrorResponse {
                error: self.user_message(),
                details: None,
            },
        };

        (status, Json(response)).into_response()
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.user_message())
    }
}

impl std::error::Error for ApiError {}

// ============================================================================
// Conversions from common error types
// ============================================================================

/// Convert `SeaORM` `DbErr` to `ApiError`
///
/// **Conversion Rules:**
/// - `DbErr::RecordNotFound` → 404 Not Found
/// - All other `DbErr` variants → 500 Internal Server Error (logged internally, sanitized for users)
///
/// **Note:** Lifecycle hooks that return `Result<(), DbErr>` can only produce 404 or 500 errors.
/// If you need custom status codes (400, 401, 403, 409), handle errors at the handler level
/// or create custom handlers that don't use the trait system.
///
/// # Examples
///
/// ```rust,ignore
/// // In lifecycle hooks - limited to 500 or 404
/// async fn before_delete(&self, db: &DatabaseConnection, id: Uuid) -> Result<(), DbErr> {
///     if !user_has_permission(id) {
///         // This will become a 500 Internal Server Error
///         return Err(DbErr::Custom("Permission check failed".into()));
///     }
///     Ok(())
/// }
///
/// // For custom status codes, use ApiError directly in your custom handlers:
/// async fn delete_with_permission(
///     State(db): State<DatabaseConnection>,
///     Path(id): Path<Uuid>,
/// ) -> Result<StatusCode, ApiError> {
///     if !check_permission(id) {
///         return Err(ApiError::forbidden("You don't have permission to delete this resource"));
///     }
///     // ... rest of delete logic
///     Ok(StatusCode::NO_CONTENT)
/// }
/// ```
impl From<DbErr> for ApiError {
    fn from(err: DbErr) -> Self {
        match &err {
            DbErr::RecordNotFound(msg) => {
                // Try to extract resource name from error message
                let resource = msg.split_whitespace().next().unwrap_or("Resource");
                Self::NotFound {
                    resource: resource.to_string(),
                    id: None,
                }
            }
            // All other database errors become 500 Internal Server Error
            _ => Self::Database {
                message: "A database error occurred".to_string(),
                internal: err,
            },
        }
    }
}

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

    // ============================================================================
    // Constructor Tests
    // ============================================================================

    #[test]
    fn test_not_found_with_id() {
        let err = ApiError::not_found("User", Some("123".to_string()));
        assert_eq!(err.status_code(), StatusCode::NOT_FOUND);
        assert_eq!(err.user_message(), "User with ID '123' not found");
    }

    #[test]
    fn test_not_found_without_id() {
        let err = ApiError::not_found("User", None);
        assert_eq!(err.status_code(), StatusCode::NOT_FOUND);
        assert_eq!(err.user_message(), "User not found");
    }

    #[test]
    fn test_bad_request() {
        let err = ApiError::bad_request("Invalid email format");
        assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
        assert_eq!(err.user_message(), "Invalid email format");
    }

    #[test]
    fn test_unauthorized() {
        let err = ApiError::unauthorized("Invalid credentials");
        assert_eq!(err.status_code(), StatusCode::UNAUTHORIZED);
        assert_eq!(err.user_message(), "Invalid credentials");
    }

    #[test]
    fn test_forbidden() {
        let err = ApiError::forbidden("Insufficient permissions");
        assert_eq!(err.status_code(), StatusCode::FORBIDDEN);
        assert_eq!(err.user_message(), "Insufficient permissions");
    }

    #[test]
    fn test_conflict() {
        let err = ApiError::conflict("Email already exists");
        assert_eq!(err.status_code(), StatusCode::CONFLICT);
        assert_eq!(err.user_message(), "Email already exists");
    }

    #[test]
    fn test_validation_failed_single_error() {
        let err = ApiError::validation_failed(vec!["Email is required".to_string()]);
        assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(err.user_message(), "Email is required");
    }

    #[test]
    fn test_validation_failed_multiple_errors() {
        let err = ApiError::validation_failed(vec![
            "Email is required".to_string(),
            "Password too short".to_string(),
        ]);
        assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(
            err.user_message(),
            "Validation failed: Email is required, Password too short"
        );
    }

    #[test]
    fn test_database_error() {
        let db_err = DbErr::Type("Type mismatch error".to_string());
        let err = ApiError::database(db_err);
        assert_eq!(err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.user_message(), "A database error occurred");
    }

    #[test]
    fn test_internal_error_with_details() {
        let err = ApiError::internal(
            "Processing failed",
            Some("Null pointer exception".to_string()),
        );
        assert_eq!(err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.user_message(), "Processing failed");
    }

    #[test]
    fn test_internal_error_without_details() {
        let err = ApiError::internal("Processing failed", None);
        assert_eq!(err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.user_message(), "Processing failed");
    }

    #[test]
    fn test_custom_error() {
        let err = ApiError::custom(
            StatusCode::TOO_MANY_REQUESTS,
            "Rate limit exceeded",
            Some("User hit 100 req/min".to_string()),
        );
        assert_eq!(err.status_code(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(err.user_message(), "Rate limit exceeded");
    }

    // ============================================================================
    // DbErr Conversion Tests (Hook Error Patterns)
    // ============================================================================

    #[test]
    fn test_dberr_record_not_found_conversion() {
        let db_err = DbErr::RecordNotFound("User not found".to_string());
        let api_err: ApiError = db_err.into();
        assert_eq!(api_err.status_code(), StatusCode::NOT_FOUND);
        assert!(api_err.user_message().contains("not found"));
    }

    #[test]
    fn test_dberr_custom_becomes_internal() {
        // All DbErr::Custom variants become 500 Internal Server Error
        let db_err = DbErr::Custom("Something went wrong".to_string());
        let api_err: ApiError = db_err.into();
        assert_eq!(api_err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.user_message(), "A database error occurred");
    }

    #[test]
    fn test_dberr_type_error() {
        let db_err = DbErr::Type("Type conversion failed".to_string());
        let api_err: ApiError = db_err.into();
        assert_eq!(api_err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.user_message(), "A database error occurred");
    }

    #[test]
    fn test_dberr_json_error() {
        let db_err = DbErr::Json("JSON parsing failed".to_string());
        let api_err: ApiError = db_err.into();
        assert_eq!(api_err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.user_message(), "A database error occurred");
    }

    // ============================================================================
    // DbErr Conversion Tests - Simple Behavior
    // ============================================================================

    #[test]
    fn test_dberr_record_not_found_becomes_404() {
        // DbErr::RecordNotFound becomes 404
        let db_err = DbErr::RecordNotFound("Blog post not found".to_string());
        let api_err: ApiError = db_err.into();
        assert_eq!(api_err.status_code(), StatusCode::NOT_FOUND);
        assert!(api_err.user_message().contains("not found"));
    }

    #[test]
    fn test_all_other_dberr_become_500() {
        // All other DbErr types become 500 Internal Server Error
        let test_cases = vec![
            DbErr::Custom("Any custom error".to_string()),
            DbErr::Type("Type error".to_string()),
            DbErr::Json("JSON error".to_string()),
        ];

        for db_err in test_cases {
            let api_err: ApiError = db_err.into();
            assert_eq!(api_err.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
            assert_eq!(api_err.user_message(), "A database error occurred");
        }
    }

    // ============================================================================
    // Display and Error Trait Tests
    // ============================================================================

    #[test]
    fn test_display_trait() {
        let err = ApiError::bad_request("Test error");
        assert_eq!(format!("{}", err), "Test error");
    }

    #[test]
    fn test_error_trait() {
        let err = ApiError::bad_request("Test error");
        let _: &dyn std::error::Error = &err; // Verify it implements Error trait
    }

    // ============================================================================
    // Status Code Coverage Tests
    // ============================================================================

    #[test]
    fn test_all_status_codes() {
        let test_cases = vec![
            (ApiError::not_found("Test", None), StatusCode::NOT_FOUND),
            (ApiError::bad_request("Test"), StatusCode::BAD_REQUEST),
            (ApiError::unauthorized("Test"), StatusCode::UNAUTHORIZED),
            (ApiError::forbidden("Test"), StatusCode::FORBIDDEN),
            (ApiError::conflict("Test"), StatusCode::CONFLICT),
            (
                ApiError::validation_failed(vec!["Test".to_string()]),
                StatusCode::UNPROCESSABLE_ENTITY,
            ),
            (
                ApiError::database(DbErr::Conn(sea_orm::RuntimeErr::Internal(
                    "Test".to_string(),
                ))),
                StatusCode::INTERNAL_SERVER_ERROR,
            ),
            (
                ApiError::internal("Test", None),
                StatusCode::INTERNAL_SERVER_ERROR,
            ),
            (
                ApiError::custom(StatusCode::IM_A_TEAPOT, "Test", None),
                StatusCode::IM_A_TEAPOT,
            ),
        ];

        for (err, expected_status) in test_cases {
            assert_eq!(err.status_code(), expected_status);
        }
    }
}