Skip to main content

anycms_core/
result.rs

1use crate::pagination::ResultPagination;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4
5// ============================================================
6// Error Codes
7// ============================================================
8
9/// Standard error codes for API responses
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[repr(i32)]
12#[non_exhaustive]
13pub enum ErrorCode {
14    Success = 0,
15    BadRequest = 400,
16    Unauthorized = 401,
17    Forbidden = 403,
18    NotFound = 404,
19    MethodNotAllowed = 405,
20    Conflict = 409,
21    PayloadTooLarge = 413,
22    ValidationError = 422,
23    TooManyRequests = 429,
24    InternalError = 500,
25    ServiceUnavailable = 503,
26}
27
28impl ErrorCode {
29    /// Get the integer representation of the error code
30    pub fn as_i32(self) -> i32 {
31        self as i32
32    }
33
34    /// Convert error code to HTTP status message
35    pub fn as_str(self) -> &'static str {
36        match self {
37            ErrorCode::Success => "Success",
38            ErrorCode::BadRequest => "Bad Request",
39            ErrorCode::Unauthorized => "Unauthorized",
40            ErrorCode::Forbidden => "Forbidden",
41            ErrorCode::NotFound => "Not Found",
42            ErrorCode::MethodNotAllowed => "Method Not Allowed",
43            ErrorCode::Conflict => "Conflict",
44            ErrorCode::PayloadTooLarge => "Payload Too Large",
45            ErrorCode::ValidationError => "Unprocessable Entity",
46            ErrorCode::TooManyRequests => "Too Many Requests",
47            ErrorCode::InternalError => "Internal Server Error",
48            ErrorCode::ServiceUnavailable => "Service Unavailable",
49        }
50    }
51
52    /// Try to convert an integer to an ErrorCode
53    pub fn from_i32(value: i32) -> Option<Self> {
54        match value {
55            0 => Some(ErrorCode::Success),
56            400 => Some(ErrorCode::BadRequest),
57            401 => Some(ErrorCode::Unauthorized),
58            403 => Some(ErrorCode::Forbidden),
59            404 => Some(ErrorCode::NotFound),
60            405 => Some(ErrorCode::MethodNotAllowed),
61            409 => Some(ErrorCode::Conflict),
62            413 => Some(ErrorCode::PayloadTooLarge),
63            422 => Some(ErrorCode::ValidationError),
64            429 => Some(ErrorCode::TooManyRequests),
65            500 => Some(ErrorCode::InternalError),
66            503 => Some(ErrorCode::ServiceUnavailable),
67            _ => None,
68        }
69    }
70}
71
72// ============================================================
73// Field-level Validation Errors
74// ============================================================
75
76/// A single field-level validation error
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[cfg_attr(not(feature = "snake-case"), serde(rename_all = "camelCase"))]
79#[cfg_attr(feature = "snake-case", serde(rename_all = "snake_case"))]
80pub struct FieldError {
81    pub field: String,
82    pub message: String,
83}
84
85impl FieldError {
86    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
87        Self {
88            field: field.into(),
89            message: message.into(),
90        }
91    }
92}
93
94// ============================================================
95// Response Data Types
96// ============================================================
97
98/// Response data wrapper that can hold either a single value or a list
99#[derive(Debug, Clone, Serialize, Deserialize, Default)]
100#[serde(untagged)]
101#[non_exhaustive]
102pub enum ResponseData<T> {
103    /// A single value
104    Single(T),
105    /// A list of values
106    Multiple(Vec<T>),
107    /// No data
108    #[default]
109    Empty,
110}
111
112impl<T> ResponseData<T> {
113    /// Create a single value response data
114    pub fn single(v: T) -> Self {
115        ResponseData::Single(v)
116    }
117
118    /// Create a multiple values response data
119    pub fn multiple(v: Vec<T>) -> Self {
120        ResponseData::Multiple(v)
121    }
122
123    /// Check if this is a single value
124    pub fn is_single(&self) -> bool {
125        matches!(self, ResponseData::Single(_))
126    }
127
128    /// Check if this is multiple values
129    pub fn is_multiple(&self) -> bool {
130        matches!(self, ResponseData::Multiple(_))
131    }
132
133    /// Check if this is empty
134    pub fn is_empty(&self) -> bool {
135        matches!(self, ResponseData::Empty)
136    }
137
138    /// Get reference to the single value, if present
139    pub fn as_single(&self) -> Option<&T> {
140        match self {
141            ResponseData::Single(v) => Some(v),
142            _ => None,
143        }
144    }
145
146    /// Get reference to the multiple values, if present
147    pub fn as_multiple(&self) -> Option<&Vec<T>> {
148        match self {
149            ResponseData::Multiple(v) => Some(v),
150            _ => None,
151        }
152    }
153
154    /// Number of items in the data: 1 for `Single`, vec len for `Multiple`, 0 for `Empty`
155    #[inline]
156    pub fn len(&self) -> usize {
157        match self {
158            ResponseData::Single(_) => 1,
159            ResponseData::Multiple(v) => v.len(),
160            ResponseData::Empty => 0,
161        }
162    }
163
164    /// Whether the data carries no items.
165    ///
166    /// Different from `is_empty()` which checks the `Empty` variant.
167    /// `Multiple(vec![])` has `is_empty_data() == true` but `is_empty() == false`.
168    #[inline]
169    #[allow(clippy::len_zero)]
170    pub fn is_empty_data(&self) -> bool {
171        self.len() == 0
172    }
173}
174
175impl<T> From<T> for ResponseData<T> {
176    fn from(v: T) -> Self {
177        ResponseData::Single(v)
178    }
179}
180
181impl<T> From<Vec<T>> for ResponseData<T> {
182    fn from(v: Vec<T>) -> Self {
183        ResponseData::Multiple(v)
184    }
185}
186
187// ============================================================
188// API Response Types
189// ============================================================
190
191/// API response wrapper with unified structure
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[cfg_attr(not(feature = "snake-case"), serde(rename_all = "camelCase"))]
194#[cfg_attr(feature = "snake-case", serde(rename_all = "snake_case"))]
195pub struct ApiResult<T> {
196    pub success: bool,
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub data: Option<ResponseData<T>>,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub message: Option<String>,
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub code: Option<i32>,
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub pagination: Option<ResultPagination>,
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub errors: Option<Vec<FieldError>>,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub trace_id: Option<String>,
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub biz_code: Option<i32>,
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub timestamp: Option<i64>,
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub extra: Option<Value>,
215}
216
217impl<T> ApiResult<T> {
218    // ── Internal constructor ──
219
220    /// Internal constructor that creates the base struct with all optional fields as None.
221    #[inline]
222    fn new(
223        success: bool,
224        data: Option<ResponseData<T>>,
225        message: Option<String>,
226        code: Option<i32>,
227    ) -> Self {
228        ApiResult {
229            success,
230            data,
231            message,
232            code,
233            pagination: None,
234            errors: None,
235            trace_id: None,
236            biz_code: None,
237            timestamp: None,
238            extra: None,
239        }
240    }
241
242    // ── Factory methods ──
243
244    /// Create a successful response with a single value
245    #[inline]
246    pub fn value(v: T) -> Self {
247        Self::new(true, Some(ResponseData::single(v)), None, None)
248    }
249
250    /// Create a successful response with a list of values
251    #[inline]
252    pub fn list(v: Vec<T>) -> Self {
253        Self::new(true, Some(ResponseData::multiple(v)), None, None)
254    }
255
256    /// Create a failed response with a message (alias for `failure`)
257    #[inline]
258    pub fn fail(message: &str) -> Self {
259        Self::failure(message)
260    }
261
262    /// Create a failed response with a message
263    #[inline]
264    pub fn failure(message: &str) -> Self {
265        Self::new(false, None, Some(message.to_string()), None)
266    }
267
268    /// Create a successful response without data
269    ///
270    /// Alias for `ok()` - use `ok()` for clarity
271    #[inline]
272    pub fn success() -> Self {
273        Self::ok()
274    }
275
276    /// Create a successful response without data (recommended method name)
277    #[inline]
278    pub fn ok() -> Self {
279        Self::new(true, None, None, None)
280    }
281
282    /// Create a validation error response with field-level details
283    pub fn validation_errors(errors: Vec<FieldError>) -> Self {
284        let mut r = Self::new(
285            false,
286            None,
287            Some("Validation failed".to_string()),
288            Some(ErrorCode::ValidationError as i32),
289        );
290        r.errors = Some(errors);
291        r
292    }
293
294    /// Convert a `Result<T, E>` into `ApiResult<T>`, mapping all errors to `InternalError`
295    pub fn from_result<E: std::fmt::Display>(result: Result<T, E>) -> Self {
296        match result {
297            Ok(data) => Self::value(data),
298            Err(err) => Self::new(
299                false,
300                None,
301                Some(err.to_string()),
302                Some(ErrorCode::InternalError as i32),
303            ),
304        }
305    }
306
307    // ── Query methods ──
308
309    /// Whether this is a successful response
310    #[inline]
311    pub fn is_success(&self) -> bool {
312        self.success
313    }
314
315    /// Whether this is an error response
316    #[inline]
317    pub fn is_error(&self) -> bool {
318        !self.success
319    }
320
321    /// Get the error code if this is an error response
322    pub fn error_code(&self) -> Option<ErrorCode> {
323        if !self.success {
324            self.code.and_then(ErrorCode::from_i32)
325        } else {
326            None
327        }
328    }
329
330    // ── Builder methods ──
331
332    /// Add extra metadata to the response
333    #[inline]
334    pub fn with_extra(mut self, key: &str, value: Value) -> Self {
335        match self.extra {
336            Some(ref mut v) => {
337                v[key] = value;
338            }
339            None => {
340                let mut v = serde_json::Map::new();
341                v.insert(key.to_string(), value);
342                self.extra = Some(v.into());
343            }
344        }
345        self
346    }
347
348    /// Set error code for the response
349    #[inline]
350    pub fn with_code(mut self, code: i32) -> Self {
351        self.code = Some(code);
352        self
353    }
354
355    /// Set pagination metadata for list responses
356    #[inline]
357    pub fn with_pagination(mut self, pagination: ResultPagination) -> Self {
358        self.pagination = Some(pagination);
359        self
360    }
361
362    /// Set message for the response
363    #[inline]
364    pub fn with_message(mut self, message: &str) -> Self {
365        self.message = Some(message.to_string());
366        self
367    }
368
369    /// Set field-level validation errors
370    #[inline]
371    pub fn with_errors(mut self, errors: Vec<FieldError>) -> Self {
372        self.errors = Some(errors);
373        self
374    }
375
376    /// Add a single field-level validation error
377    #[inline]
378    pub fn with_error(mut self, field: impl Into<String>, message: impl Into<String>) -> Self {
379        match self.errors {
380            Some(ref mut v) => v.push(FieldError::new(field, message)),
381            None => self.errors = Some(vec![FieldError::new(field, message)]),
382        }
383        self
384    }
385
386    /// Set request trace ID
387    #[inline]
388    pub fn with_trace_id(mut self, id: impl Into<String>) -> Self {
389        self.trace_id = Some(id.into());
390        self
391    }
392
393    /// Set business error code (independent of HTTP status code)
394    #[inline]
395    pub fn with_biz_code(mut self, code: i32) -> Self {
396        self.biz_code = Some(code);
397        self
398    }
399
400    /// Set timestamp (Unix milliseconds)
401    #[inline]
402    pub fn with_timestamp(mut self, ts: i64) -> Self {
403        self.timestamp = Some(ts);
404        self
405    }
406
407    /// Set timestamp to current time automatically
408    pub fn with_current_timestamp(self) -> Self {
409        use std::time::{SystemTime, UNIX_EPOCH};
410        let ts = SystemTime::now()
411            .duration_since(UNIX_EPOCH)
412            .map(|d| d.as_millis() as i64)
413            .unwrap_or(0);
414        self.with_timestamp(ts)
415    }
416}
417
418// ============================================================
419// ApiResult -> Result conversion (used by downstream handlers)
420// ============================================================
421
422/// Convert `ApiResult<T>` into `Result<ApiResult<T>, E>` for any error type `E`.
423///
424/// This allows `ApiResult::value(data).into()` to work as a shorthand for
425/// `Ok(ApiResult::value(data))` in handlers returning `DefaultResult<impl Responder>`.
426///
427/// The conversion always produces `Ok` — the `Err` variant is never used because
428/// `ApiResult` itself encodes success/failure in its `success` field.
429impl<T, E> From<ApiResult<T>> for Result<ApiResult<T>, E> {
430    fn from(val: ApiResult<T>) -> Self {
431        Ok(val)
432    }
433}
434
435// ============================================================
436// From Implementations for Error Conversion
437// ============================================================
438
439impl<T> From<anyhow::Error> for ApiResult<T> {
440    fn from(err: anyhow::Error) -> Self {
441        Self::new(
442            false,
443            None,
444            Some(err.to_string()),
445            Some(ErrorCode::InternalError as i32),
446        )
447    }
448}
449
450impl<T> From<std::io::Error> for ApiResult<T> {
451    fn from(err: std::io::Error) -> Self {
452        Self::new(
453            false,
454            None,
455            Some(err.to_string()),
456            Some(ErrorCode::InternalError as i32),
457        )
458    }
459}
460
461impl<T> From<std::string::FromUtf8Error> for ApiResult<T> {
462    fn from(err: std::string::FromUtf8Error) -> Self {
463        Self::new(
464            false,
465            None,
466            Some(err.to_string()),
467            Some(ErrorCode::InternalError as i32),
468        )
469    }
470}
471
472/// Convert any `Result<T, E>` where E implements Display to `ApiResult<T>`
473impl<T, E: std::fmt::Display + std::fmt::Debug> From<Result<T, E>> for ApiResult<T> {
474    fn from(result: Result<T, E>) -> Self {
475        match result {
476            Ok(data) => Self::value(data),
477            Err(err) => Self::new(
478                false,
479                None,
480                Some(format!("{}", err)),
481                Some(ErrorCode::InternalError as i32),
482            ),
483        }
484    }
485}
486
487/// Type alias for standard Result with `Box<dyn Error>`.
488///
489/// Commonly used as the return type for API handlers:
490/// `-> DefaultResult<impl Responder>` where `Ok(ApiResult::value(data))` is returned.
491pub type DefaultResult<T> = Result<T, Box<dyn std::error::Error>>;