//! 新版契约响应信封:HTTP 200 + `{code, msg, data}`。 //! //! ⚠️ **鉴权失败不走本信封** —— 上游 `TdcAuthFilter` 回的是 //! `{"success":false,"code":401,"msg":"…"}`(**无 `data`、多 `success:false`**)。 //! 两套形状必须分开实现,见 `auth::reject`。 use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::Json; use serde::Serialize; use serde_json::Value; pub const CODE_OK: i32 = 200; pub const CODE_FAIL: i32 = 400; pub const CODE_FORBIDDEN: i32 = 403; pub const CODE_SERVER_ERROR: i32 = 500; pub const CODE_SESSION_EXPIRED: i32 = 600; #[derive(Debug, Clone, Serialize)] pub struct ActionResult { pub code: i32, pub msg: Option, pub data: Option, } impl ActionResult { pub fn ok(data: T) -> Self { Self { code: CODE_OK, msg: None, data: Some(data), } } pub fn ok_msg(msg: impl Into, data: T) -> Self { Self { code: CODE_OK, msg: Some(msg.into()), data: Some(data), } } } impl ActionResult { /// 业务失败:**HTTP 仍为 200**,用 body 的 `code` 表达失败。 pub fn fail(msg: impl Into) -> Self { Self { code: CODE_FAIL, msg: Some(msg.into()), data: None, } } pub fn fail_code(code: i32, msg: impl Into) -> Self { Self { code, msg: Some(msg.into()), data: None, } } /// 分页列表:`{pagination:{currentPage,pageSize,total}, list:[…]}`。 pub fn page(list: Vec, pagination: Pagination) -> Self { let data = serde_json::to_value(PageData { pagination, list }) .expect("PageData 一定可序列化"); Self { code: CODE_OK, msg: None, data: Some(data), } } } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Pagination { pub current_page: i64, pub page_size: i64, pub total: i64, } #[derive(Debug, Clone, Serialize)] pub struct PageData { pub pagination: Pagination, pub list: Vec, } /// 业务信封 → HTTP 响应。 /// /// 🔴 **状态码恒为 200**,无论 `self.code` 是多少 —— 业务成败只由 body 的 `code` 表达 /// (全局约束:业务失败一律 HTTP 200 + `{code,msg,data}`)。 /// /// ⚠️ 本 impl 只服务**业务信封**。鉴权失败(401/403)是另一套形状 /// `{"success":false,"code":401,"msg":"…"}`(无 `data`),由鉴权层单独实现, /// **不要**塞进本信封。 impl IntoResponse for ActionResult { fn into_response(self) -> Response { (StatusCode::OK, Json(self)).into_response() } } #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] fn ok_has_null_msg_and_wrapped_data() { let r = ActionResult::ok(json!({"a": 1})); assert_eq!( serde_json::to_value(&r).unwrap(), json!({"code": 200, "msg": null, "data": {"a": 1}}) ); } #[test] fn write_ops_carry_the_chinese_message() { let r = ActionResult::ok_msg("新增成功", "12345"); assert_eq!( serde_json::to_value(&r).unwrap(), json!({"code": 200, "msg": "新增成功", "data": "12345"}) ); } #[test] fn business_failure_is_still_http_200_with_code_400() { let r = ActionResult::fail("记录不存在或已删除"); assert_eq!( serde_json::to_value(&r).unwrap(), json!({"code": 400, "msg": "记录不存在或已删除", "data": null}) ); } #[test] fn page_shape_matches_jnpf_pagelistvo() { let r = ActionResult::page( vec![json!({"id": "1"})], Pagination { current_page: 2, page_size: 20, total: 41, }, ); assert_eq!( serde_json::to_value(&r).unwrap(), json!({ "code": 200, "msg": null, "data": { "pagination": {"currentPage": 2, "pageSize": 20, "total": 41}, "list": [{"id": "1"}] } }) ); } /// 🔴 业务失败也必须回 HTTP **200**;成败只由 body 的 `code` 表达。 #[tokio::test] async fn into_response_keeps_http_200_for_business_failure() { let resp = ActionResult::fail("记录不存在或已删除").into_response(); assert_eq!(resp.status(), StatusCode::OK, "业务失败不得走 4xx"); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .expect("读 body"); let v: Value = serde_json::from_slice(&body).expect("body 是 JSON"); assert_eq!(v["code"], 400); assert_eq!(v["msg"], "记录不存在或已删除"); assert!(v["data"].is_null()); } #[tokio::test] async fn into_response_of_ok_is_http_200_with_wrapped_data() { let resp = ActionResult::ok(json!({"a": 1})).into_response(); assert_eq!(resp.status(), StatusCode::OK); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .expect("读 body"); let v: Value = serde_json::from_slice(&body).expect("body 是 JSON"); assert_eq!(v["code"], 200); assert_eq!(v["data"], json!({"a": 1})); } }