anycms-core 0.4.0

A unified API response library supporting multiple Rust web frameworks
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
use crate::pagination::ResultPagination;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

// ============================================================
// Error Types & Codes
// ============================================================

/// Standard error codes for API responses
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum ErrorCode {
    Success = 0,
    BadRequest = 400,
    Unauthorized = 401,
    Forbidden = 403,
    NotFound = 404,
    Conflict = 409,
    ValidationError = 422,
    InternalError = 500,
    NotImplemented = 501,
    BadGateway = 502,
    ServiceUnavailable = 503,
}

impl ErrorCode {
    /// Get the integer representation of the error code
    pub fn as_i32(self) -> i32 {
        self as i32
    }

    /// Convert error code to HTTP status message
    pub fn as_str(self) -> &'static str {
        match self {
            ErrorCode::Success => "Success",
            ErrorCode::BadRequest => "Bad Request",
            ErrorCode::Unauthorized => "Unauthorized",
            ErrorCode::Forbidden => "Forbidden",
            ErrorCode::NotFound => "Not Found",
            ErrorCode::Conflict => "Conflict",
            ErrorCode::ValidationError => "Unprocessable Entity",
            ErrorCode::InternalError => "Internal Server Error",
            ErrorCode::NotImplemented => "Not Implemented",
            ErrorCode::BadGateway => "Bad Gateway",
            ErrorCode::ServiceUnavailable => "Service Unavailable",
        }
    }

    /// Try to convert an integer to an ErrorCode
    pub fn from_i32(value: i32) -> Option<Self> {
        match value {
            0 => Some(ErrorCode::Success),
            400 => Some(ErrorCode::BadRequest),
            401 => Some(ErrorCode::Unauthorized),
            403 => Some(ErrorCode::Forbidden),
            404 => Some(ErrorCode::NotFound),
            409 => Some(ErrorCode::Conflict),
            422 => Some(ErrorCode::ValidationError),
            500 => Some(ErrorCode::InternalError),
            501 => Some(ErrorCode::NotImplemented),
            502 => Some(ErrorCode::BadGateway),
            503 => Some(ErrorCode::ServiceUnavailable),
            _ => None,
        }
    }

    /// Convert to Axum StatusCode (requires axum feature)
    #[cfg(feature = "axum")]
    pub fn to_axum_status(self) -> axum::http::StatusCode {
        match self {
            ErrorCode::Success => axum::http::StatusCode::OK,
            ErrorCode::BadRequest => axum::http::StatusCode::BAD_REQUEST,
            ErrorCode::Unauthorized => axum::http::StatusCode::UNAUTHORIZED,
            ErrorCode::Forbidden => axum::http::StatusCode::FORBIDDEN,
            ErrorCode::NotFound => axum::http::StatusCode::NOT_FOUND,
            ErrorCode::Conflict => axum::http::StatusCode::CONFLICT,
            ErrorCode::ValidationError => axum::http::StatusCode::UNPROCESSABLE_ENTITY,
            ErrorCode::InternalError => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            ErrorCode::NotImplemented => axum::http::StatusCode::NOT_IMPLEMENTED,
            ErrorCode::BadGateway => axum::http::StatusCode::BAD_GATEWAY,
            ErrorCode::ServiceUnavailable => axum::http::StatusCode::SERVICE_UNAVAILABLE,
        }
    }

    /// Convert to Actix-web StatusCode (requires actix feature)
    #[cfg(feature = "actix")]
    pub fn to_actix_status(self) -> actix_web::http::StatusCode {
        match self {
            ErrorCode::Success => actix_web::http::StatusCode::OK,
            ErrorCode::BadRequest => actix_web::http::StatusCode::BAD_REQUEST,
            ErrorCode::Unauthorized => actix_web::http::StatusCode::UNAUTHORIZED,
            ErrorCode::Forbidden => actix_web::http::StatusCode::FORBIDDEN,
            ErrorCode::NotFound => actix_web::http::StatusCode::NOT_FOUND,
            ErrorCode::Conflict => actix_web::http::StatusCode::CONFLICT,
            ErrorCode::ValidationError => actix_web::http::StatusCode::UNPROCESSABLE_ENTITY,
            ErrorCode::InternalError => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
            ErrorCode::NotImplemented => actix_web::http::StatusCode::NOT_IMPLEMENTED,
            ErrorCode::BadGateway => actix_web::http::StatusCode::BAD_GATEWAY,
            ErrorCode::ServiceUnavailable => actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
        }
    }
}

/// Standard API error with error code and message
///
/// This error type can be used directly or as a base for custom error types.
///
/// # Example
/// ```rust
/// use anycms_core::{ApiError, ErrorCode};
///
/// // Create error directly
/// let err = ApiError::new(ErrorCode::NotFound, "User not found");
///
/// // Use convenience methods
/// let err = ApiError::not_found("User not found");
/// let err = ApiError::bad_request("Invalid email format");
/// ```
#[derive(Error, Debug)]
pub struct ApiError {
    pub code: ErrorCode,
    pub message: String,
}

impl ApiError {
    /// Create a new ApiError with the given code and message
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }

    /// Create a NotFound error (404)
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotFound, message)
    }

    /// Create a BadRequest error (400)
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::BadRequest, message)
    }

    /// Create an Unauthorized error (401)
    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::Unauthorized, message)
    }

    /// Create a Forbidden error (403)
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::Forbidden, message)
    }

    /// Create a ValidationError error (422)
    pub fn validation(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::ValidationError, message)
    }

    /// Create a Conflict error (409)
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::Conflict, message)
    }

    /// Create an InternalError (500)
    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InternalError, message)
    }

    /// Get the error code
    pub fn code(&self) -> ErrorCode {
        self.code
    }

    /// Get reference to the error message
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.code.as_str(), self.message)
    }
}

/// Generic application error that can represent any error type
///
/// This is a catch-all error type that can wrap any error that implements
/// `std::error::Error + Send + Sync + 'static`.
#[derive(Error, Debug)]
pub enum AppError {
    #[error("Resource not found: {0}")]
    NotFound(String),

    #[error("Bad request: {0}")]
    BadRequest(String),

    #[error("Unauthorized: {0}")]
    Unauthorized(String),

    #[error("Forbidden: {0}")]
    Forbidden(String),

    #[error("Conflict: {0}")]
    Conflict(String),

    #[error("Validation error: {0}")]
    Validation(String),

    #[error("Internal error: {0}")]
    Internal(#[from] anyhow::Error),

    #[error("Unknown error: {0}")]
    Unknown(String),
}

impl AppError {
    /// Convert AppError to ErrorCode
    pub fn to_error_code(&self) -> ErrorCode {
        match self {
            AppError::NotFound(_) => ErrorCode::NotFound,
            AppError::BadRequest(_) => ErrorCode::BadRequest,
            AppError::Unauthorized(_) => ErrorCode::Unauthorized,
            AppError::Forbidden(_) => ErrorCode::Forbidden,
            AppError::Conflict(_) => ErrorCode::Conflict,
            AppError::Validation(_) => ErrorCode::ValidationError,
            AppError::Internal(_) => ErrorCode::InternalError,
            AppError::Unknown(_) => ErrorCode::InternalError,
        }
    }
}

impl From<ApiError> for AppError {
    fn from(err: ApiError) -> Self {
        match err.code {
            ErrorCode::NotFound => AppError::NotFound(err.message),
            ErrorCode::BadRequest => AppError::BadRequest(err.message),
            ErrorCode::Unauthorized => AppError::Unauthorized(err.message),
            ErrorCode::Forbidden => AppError::Forbidden(err.message),
            ErrorCode::Conflict => AppError::Conflict(err.message),
            ErrorCode::ValidationError => AppError::Validation(err.message),
            _ => AppError::Internal(anyhow::anyhow!(err.message)),
        }
    }
}

// ============================================================
// Response Data Types
// ============================================================

/// Response data wrapper that can hold either a single value or a list
///
/// This enum uses `#[serde(untagged)]` to serialize directly as the contained value,
/// allowing a single `data` field to represent both single values and lists.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResponseData<T> {
    /// A single value
    Single(T),
    /// A list of values
    Multiple(Vec<T>),
}

impl<T> ResponseData<T> {
    /// Create a single value response data
    pub fn single(v: T) -> Self {
        ResponseData::Single(v)
    }

    /// Create a multiple values response data
    pub fn multiple(v: Vec<T>) -> Self {
        ResponseData::Multiple(v)
    }

    /// Check if this is a single value
    pub fn is_single(&self) -> bool {
        matches!(self, ResponseData::Single(_))
    }

    /// Check if this is multiple values
    pub fn is_multiple(&self) -> bool {
        matches!(self, ResponseData::Multiple(_))
    }

    /// Get reference to the single value, if present
    pub fn as_single(&self) -> Option<&T> {
        match self {
            ResponseData::Single(v) => Some(v),
            ResponseData::Multiple(_) => None,
        }
    }

    /// Get reference to the multiple values, if present
    pub fn as_multiple(&self) -> Option<&Vec<T>> {
        match self {
            ResponseData::Single(_) => None,
            ResponseData::Multiple(v) => Some(v),
        }
    }
}

// ============================================================
// API Response Types
// ============================================================

/// API response wrapper with unified structure
///
/// # Fields
/// - `success`: Indicates if the request was successful
/// - `data`: Contains either a single value or a list (via `ResponseData`)
/// - `message`: Optional message or error description
/// - `code`: Optional error code
/// - `pagination`: Optional pagination metadata for list responses
/// - `extra`: Additional metadata as key-value pairs
///
/// # JSON Serialization Examples
/// ```json
/// // Single value
/// { "success": true, "data": { "id": 1, "name": "Alice" } }
///
/// // List
/// { "success": true, "data": [{ "id": 1 }, { "id": 2 }], "pagination": {...} }
///
/// // Empty success
/// { "success": true }
///
/// // Error
/// { "success": false, "message": "Not found", "code": 404 }
/// ```
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiResult<T> {
    pub success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<ResponseData<T>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pagination: Option<ResultPagination>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra: Option<Value>,
}

impl<T> ApiResult<T> {
    /// Create a successful response with a single value
    pub fn value(v: T) -> Self {
        ApiResult {
            success: true,
            data: Some(ResponseData::single(v)),
            message: None,
            code: None,
            pagination: None,
            extra: None,
        }
    }

    /// Create a successful response with a list of values
    pub fn list(v: Vec<T>) -> Self {
        ApiResult {
            success: true,
            data: Some(ResponseData::multiple(v)),
            message: None,
            code: None,
            pagination: None,
            extra: None,
        }
    }

    /// Create a failed response with a message (alias for `failure`)
    pub fn fail(message: &str) -> Self {
        Self::failure(message)
    }

    /// Create a failed response with a message
    pub fn failure(message: &str) -> Self {
        ApiResult {
            success: false,
            data: None,
            message: Some(message.to_string()),
            code: None,
            pagination: None,
            extra: None,
        }
    }

    /// Create a successful response without data
    ///
    /// Alias for `ok()` - use `ok()` for clarity to avoid confusion with the `success` field
    pub fn success() -> Self {
        Self::ok()
    }

    /// Create a successful response without data (recommended method name)
    pub fn ok() -> Self {
        ApiResult {
            success: true,
            data: None,
            message: None,
            code: None,
            pagination: None,
            extra: None,
        }
    }

    /// Add extra metadata to the response
    ///
    /// # Example
    /// ```rust
    /// use anycms_core::ApiResult;
    /// use serde_json::json;
    ///
    /// let result: ApiResult<()> = ApiResult::ok()
    ///     .with_extra("timestamp", json!(1234567890))
    ///     .with_extra("version", json!("1.0.0"));
    /// ```
    pub fn with_extra(mut self, key: &str, value: Value) -> Self {
        match self.extra {
            Some(ref mut v) => {
                v[key] = value;
            }
            None => {
                let mut v = serde_json::Map::new();
                v.insert(key.to_string(), value);
                self.extra = Some(v.into());
            }
        }
        self
    }

    /// Set error code for the response
    pub fn with_code(mut self, code: i32) -> Self {
        self.code = Some(code);
        self
    }

    /// Set pagination metadata for list responses
    pub fn with_pagination(mut self, pagination: ResultPagination) -> Self {
        self.pagination = Some(pagination);
        self
    }

    /// Set message for the response
    pub fn with_message(mut self, message: &str) -> Self {
        self.message = Some(message.to_string());
        self
    }
}

/// Conversion into Result for convenient error handling
impl<T, E> Into<Result<ApiResult<T>, E>> for ApiResult<T> {
    fn into(self) -> Result<ApiResult<T>, E> {
        Ok(self)
    }
}

// ============================================================
// From Implementations for Error Conversion
// ============================================================

impl<T> From<ApiError> for ApiResult<T> {
    fn from(err: ApiError) -> Self {
        ApiResult {
            success: false,
            data: None,
            message: Some(err.message),
            code: Some(err.code.as_i32()),
            pagination: None,
            extra: None,
        }
    }
}

impl<T> From<AppError> for ApiResult<T> {
    fn from(err: AppError) -> Self {
        ApiResult {
            success: false,
            data: None,
            message: Some(err.to_string()),
            code: Some(err.to_error_code().as_i32()),
            pagination: None,
            extra: None,
        }
    }
}

impl<T> From<anyhow::Error> for ApiResult<T> {
    fn from(err: anyhow::Error) -> Self {
        ApiResult {
            success: false,
            data: None,
            message: Some(err.to_string()),
            code: Some(ErrorCode::InternalError.as_i32()),
            pagination: None,
            extra: None,
        }
    }
}

/// Convert any `Result<T, E>` where E implements Display to `ApiResult<T>`
impl<T, E: std::fmt::Display + std::fmt::Debug> From<Result<T, E>> for ApiResult<T> {
    fn from(result: Result<T, E>) -> Self {
        match result {
            Ok(data) => ApiResult::value(data),
            Err(err) => ApiResult {
                success: false,
                data: None,
                message: Some(format!("{}", err)),
                code: Some(ErrorCode::InternalError.as_i32()),
                pagination: None,
                extra: None,
            },
        }
    }
}

/// Helper trait for converting Results to ApiResults with custom error handling
pub trait IntoApiResult<T> {
    /// Convert a Result to ApiResult, mapping errors with a provided function
    fn into_api_result_with<F>(self, f: F) -> ApiResult<T>
    where
        F: FnOnce() -> ApiError;

    /// Convert a Result to ApiResult with default error handling
    fn into_api_result(self) -> ApiResult<T>;
}

// Blanket implementation for any Result where Error can be converted to ApiError
impl<T, E: Into<ApiError>> IntoApiResult<T> for Result<T, E> {
    fn into_api_result_with<F>(self, f: F) -> ApiResult<T>
    where
        F: FnOnce() -> ApiError,
    {
        match self {
            Ok(data) => ApiResult::value(data),
            Err(_) => ApiResult::from(f()),
        }
    }

    fn into_api_result(self) -> ApiResult<T> {
        match self {
            Ok(data) => ApiResult::value(data),
            Err(err) => ApiResult::from(err.into()),
        }
    }
}

/// Type alias for standard Result with `Box<dyn Error>`
pub type DefaultResult<T> = Result<T, Box<dyn std::error::Error>>;

/// Type alias for Result with anyhow::Error
pub type AnyhowResult<T> = Result<T, anyhow::Error>;

/// API result without any data payload
///
/// Use this for endpoints that only return success/failure status
/// or endpoints that only use `extra` metadata without structured data.
///
/// # Example
/// ```rust
/// use anycms_core::EmptyResult;
///
/// // Simple success response
/// let result: EmptyResult = EmptyResult::ok();
///
/// // Error response
/// let result: EmptyResult = EmptyResult::failure("Operation failed");
/// ```
pub type EmptyResult = ApiResult<()>;