use crate::error::BaseError;
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct ApiResponse {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
}
impl ApiResponse {
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),
})
}
pub fn success_value(data: serde_json::Value, message: impl Into<String>) -> Self {
Self {
code: 0,
message: message.into(),
data: Some(data),
}
}
pub fn fail(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: None,
}
}
pub fn from_error(error: &BaseError) -> Self {
Self::fail(error.code(), error.to_string())
}
}
impl Default for ApiResponse {
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() {
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() {
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() {
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, "测试");
assert!(result.is_err(), "序列化失败应该返回错误");
if let Err(BaseError::JsonSerializeFailed(_)) = result {
} 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());
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() {
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\":\"服务器错误\""));
assert!(!json.contains("\"data\""));
}
}