yang-base 0.1.2

个人使用构建后端服务器
Documentation
//! Action 响应结构
//!
//! 提供统一的 API 响应格式,包含状态码、消息和数据。

use crate::error::BaseError;
use serde::Serialize;

/// API 响应
///
/// 统一的 API 响应格式,用于所有 Action 的返回值
///
/// # 字段
///
/// - `code`: 状态码(0 表示成功,非零表示失败)
/// - `message`: 响应消息
/// - `data`: 响应数据(可选)
///
/// 标注 `#[non_exhaustive]`:未来新增字段不构成破坏性变更。
/// 请使用 [`ApiResponse::success`] / [`ApiResponse::fail`] / [`ApiResponse::from_error`] 等构造。
///
/// # 示例
///
/// ```rust,ignore
/// use yang_base::action::ApiResponse;
/// use serde_json::json;
///
/// // 创建成功响应
/// let response = ApiResponse::success(
///     json!({ "id": 123, "name": "Alice" }),
///     "操作成功"
/// );
/// assert_eq!(response.code, 0);
///
/// // 创建失败响应
/// let response = ApiResponse::fail(400001, "参数错误");
/// assert_eq!(response.code, 400001);
/// assert!(response.data.is_none());
/// ```
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct ApiResponse {
    /// 状态码
    ///
    /// - 0: 成功
    /// - 非零: 失败(具体错误码由业务定义)
    pub code: i32,

    /// 响应消息
    ///
    /// 描述操作结果的文本信息
    pub message: String,

    /// 响应数据
    ///
    /// 成功时包含业务数据,失败时通常为 None
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

impl ApiResponse {
    /// 创建成功响应
    ///
    /// 状态码为 0,包含业务数据。序列化失败时返回 `BaseError::JsonSerializeFailed`。
    ///
    /// # 参数
    ///
    /// - `data`: 响应数据(任何可序列化的类型)
    /// - `message`: 成功消息
    ///
    /// # 返回
    ///
    /// - `Ok(ApiResponse)`: 序列化成功时返回响应实例
    /// - `Err(BaseError::JsonSerializeFailed)`: 序列化失败时返回错误
    ///
    /// # Errors
    ///
    /// - `BaseError::JsonSerializeFailed`: 当 `data` 无法被序列化为 JSON 时
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    /// use serde_json::json;
    ///
    /// // 返回单个对象
    /// let response = ApiResponse::success(
    ///     json!({ "id": 1, "name": "Alice" }),
    ///     "获取成功"
    /// )?;
    ///
    /// // 返回影响行数
    /// let response = ApiResponse::success(
    ///     json!({ "affected": 1 }),
    ///     "更新成功"
    /// )?;
    /// ```
    pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
        // 序列化数据,失败时返回结构化错误而非静默吞错
        let json_value = serde_json::to_value(data)
            .map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
        Ok(Self {
            code: 0,
            message: message.into(),
            data: Some(json_value),
        })
    }

    /// 创建成功响应(接受已序列化的 JSON 值)
    ///
    /// 当数据已经是 `serde_json::Value` 类型时,使用此方法可避免额外的序列化开销,
    /// 且不会失败,因此直接返回 `Self` 而非 `Result`。
    ///
    /// # 参数
    ///
    /// - `data`: 已序列化的 JSON 值
    /// - `message`: 成功消息
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    /// use serde_json::json;
    ///
    /// // 直接使用 serde_json::Value
    /// let data = json!({ "id": 1, "name": "Alice" });
    /// let response = ApiResponse::success_value(data, "获取成功");
    /// assert_eq!(response.code, 0);
    /// ```
    pub fn success_value(data: serde_json::Value, message: impl Into<String>) -> Self {
        Self {
            code: 0,
            message: message.into(),
            data: Some(data),
        }
    }

    /// 创建失败响应
    ///
    /// 状态码为非零错误码,不包含数据
    ///
    /// # 参数
    ///
    /// - `code`: 错误码(非零整数)
    /// - `message`: 错误消息
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    ///
    /// // 参数错误
    /// let response = ApiResponse::fail(400001, "参数缺失: username");
    ///
    /// // 权限错误
    /// let response = ApiResponse::fail(403001, "权限不足");
    ///
    /// // 业务错误
    /// let response = ApiResponse::fail(500001, "用户名已存在");
    /// ```
    pub fn fail(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }

    /// 从 BaseError 创建失败响应
    ///
    /// 自动提取错误码和错误消息。接受引用以避免消费 `BaseError` 所有权,
    /// 调用方可在构建响应的同时保留 error 用于日志记录等后续用途。
    ///
    /// # 参数
    ///
    /// - `error`: BaseError 引用
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    /// use yang_base::error::BaseError;
    ///
    /// let error = BaseError::FieldRequired("username".to_string());
    /// let response = ApiResponse::from_error(&error);
    ///
    /// assert_ne!(response.code, 0);
    /// assert!(response.message.contains("username"));
    /// assert!(response.data.is_none());
    /// ```
    pub fn from_error(error: &BaseError) -> Self {
        Self::fail(error.code(), error.to_string())
    }
}

impl Default for ApiResponse {
    /// 创建默认响应
    ///
    /// 默认为成功响应,消息为 "OK",无数据
    fn default() -> Self {
        Self {
            code: 0,
            message: "OK".to_string(),
            data: None,
        }
    }
}

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

    #[test]
    fn test_success_response() {
        // success 现在返回 Result,需要用 ? 或 unwrap
        let response =
            ApiResponse::success(json!({ "id": 123, "name": "Alice" }), "操作成功").unwrap();

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "操作成功");
        assert!(response.data.is_some());

        let data = response.data.unwrap();
        assert_eq!(data["id"], 123);
        assert_eq!(data["name"], "Alice");
    }

    #[test]
    fn test_success_response_with_null() {
        // 使用 success_value 传入已有的 JSON 值(不会失败)
        let response = ApiResponse::success_value(serde_json::Value::Null, "操作成功");

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "操作成功");
        assert!(response.data.is_some());
        assert_eq!(response.data.unwrap(), serde_json::Value::Null);
    }

    #[test]
    fn test_success_value_response() {
        // 测试 success_value 便捷构造器
        let data = json!({ "count": 42 });
        let response = ApiResponse::success_value(data, "查询成功");

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "查询成功");
        assert!(response.data.is_some());
        assert_eq!(response.data.unwrap()["count"], 42);
    }

    #[test]
    fn test_success_serialize_error_propagation() {
        // 构造一个序列化时主动返回错误的类型
        struct AlwaysFailSerialize;

        impl serde::Serialize for AlwaysFailSerialize {
            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
                use serde::ser::Error;
                Err(S::Error::custom("测试序列化失败"))
            }
        }

        let result = ApiResponse::success(AlwaysFailSerialize, "测试");
        // 序列化失败应该返回 JsonSerializeFailed 错误
        assert!(result.is_err(), "序列化失败应该返回错误");
        if let Err(BaseError::JsonSerializeFailed(_)) = result {
            // 正确:返回了 JsonSerializeFailed
        } else {
            panic!("期望 JsonSerializeFailed 错误");
        }
    }

    #[test]
    fn test_fail_response() {
        let response = ApiResponse::fail(400001, "参数错误");

        assert_eq!(response.code, 400001);
        assert_eq!(response.message, "参数错误");
        assert!(response.data.is_none());
    }

    #[test]
    fn test_from_error() {
        let error = BaseError::FieldRequired("username".to_string());
        let response = ApiResponse::from_error(&error);

        assert_ne!(response.code, 0);
        assert!(response.message.contains("username"));
        assert!(response.data.is_none());
        // error 仍可用(未被消费)
        assert_eq!(error.code(), 600006);
    }

    #[test]
    fn test_default_response() {
        let response = ApiResponse::default();

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "OK");
        assert!(response.data.is_none());
    }

    #[test]
    fn test_serialize_response() {
        // success 现在返回 Result
        let response = ApiResponse::success(json!({ "count": 10 }), "查询成功").unwrap();

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"code\":0"));
        assert!(json.contains("\"message\":\"查询成功\""));
        assert!(json.contains("\"data\""));
    }

    #[test]
    fn test_serialize_fail_response() {
        let response = ApiResponse::fail(500001, "服务器错误");

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"code\":500001"));
        assert!(json.contains("\"message\":\"服务器错误\""));
        // data 字段应该被跳过
        assert!(!json.contains("\"data\""));
    }
}