fix(routes): 空 body 的写请求回业务失败,不再建出全 null 的垃圾行

- JsonBody 去掉 Option:空 body 与畸形 JSON 走同一拒因(上游必填 @RequestBody
  ⇒ HttpMessageNotReadableException ⇒ 「请求体格式有误,请检查 JSON 结构与字段类型」)
- POST/PUT 的 body 取值改为 b.0(不再是 Option)
- 补 HTTP 级用例:空 body ⇒ HTTP 200 + code 400 + 上游原文,且不建出行
- detail_aggregate 查无分支改回 rustfmt 单行形态(仅此一处,其余历史违规不动)

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
adminandClaude Code committed 2026-10-25 02:02:34 +08:00
1 parent 5d74354944
commit 2cdbfcbcdc
4 files changed
+53 -11

No files matched your search

+1 -3
View File
@@ -922,9 +922,7 @@ pub async fn detail_aggregate(
};
let row = match rows.first() {
Some(row) => row,
None => {
return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response()
}
None => return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response(),
};
let mut data = row_to_json(row);
for (key, table) in children {
+9 -4
View File
@@ -26,8 +26,13 @@ pub const BODY_FORMAT_ERROR: &str = "请求体格式有误,请检查 JSON 结
/// 错误媒体类型会以「JSON 解析失败」的口径回报
/// (上游的 415 落到 JNPF 全局兜底,形状未知 ⇒ 这是**已登记的刻意分歧**)。
///
/// ⚠️ **空 body ⇒ `None`**(保留既有语义:POST / PUT 允许不带 body ⇒ 引擎按缺省值走)。
pub struct JsonBody(pub Option<Value>);
/// 🔴 **空 body ⇒ 业务失败**(不是 `None`):上游写端点用**必填** `@RequestBody`
/// (`ResourceController.create(@RequestBody ResourceEntity entity)`),
/// 空 body 会被 Spring 抛成 `HttpMessageNotReadableException`,
/// 再被 `SswExceptionHandler#handleNotReadable` 统一映射成
/// 「请求体格式有误,请检查 JSON 结构与字段类型」
/// ⇒ 本仓对齐:**空 body 走同一个拒因**,**不**建出一行全 null 的垃圾数据。
pub struct JsonBody(pub Value);
impl<S> FromRequest<S> for JsonBody
where
@@ -41,10 +46,10 @@ where
.await
.map_err(|_| ActionResult::fail(BODY_FORMAT_ERROR).into_response())?;
if bytes.is_empty() {
return Ok(JsonBody(None));
return Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response());
}
match serde_json::from_slice::<Value>(&bytes) {
Ok(v) => Ok(JsonBody(Some(v))),
Ok(v) => Ok(JsonBody(v)),
Err(_) => Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response()),
}
}
+3 -4
View File
@@ -8,7 +8,7 @@
//! PUT {path}/{id} 修改
//! DELETE {path}/{id} 逻辑删除
//!
//! 🔴 axum 规定**主体抽取器必须是最后一个参数** ⇒ `Option<Json<Value>>` 永远排最后,
//! 🔴 axum 规定**主体抽取器必须是最后一个参数** ⇒ `JsonBody` 永远排最后,
//! `Option<Extension<Principal>>` 排它前面。
//!
//! 🔴 路由路径**一律取 `TableSpec::path`**(注册表是唯一真源)⇒ 不另写字符串。
@@ -16,7 +16,6 @@
use axum::extract::{Extension, Path, RawQuery, State};
use axum::routing::get;
use axum::Router;
use serde_json::Value;
use super::body::JsonBody;
use crate::auth::Principal;
@@ -45,7 +44,7 @@ pub fn router() -> Router<AppState> {
p: Option<Extension<Principal>>,
b: JsonBody| {
let principal = p.map(|e| e.0);
let body = b.0.unwrap_or(Value::Null);
let body = b.0;
async move { crud::create(&st, s, &body, principal.as_ref()).await }
},
),
@@ -78,7 +77,7 @@ pub fn router() -> Router<AppState> {
p: Option<Extension<Principal>>,
b: JsonBody| {
let principal = p.map(|e| e.0);
let body = b.0.unwrap_or(Value::Null);
let body = b.0;
async move { crud::update(&st, s, &id, &body, principal.as_ref()).await }
},
)
+40
View File
@@ -434,6 +434,46 @@ async fn malformed_json_returns_the_business_envelope() {
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
}
/// 空 body 的写请求 ⇒ 业务失败(上游必填 `@RequestBody` ⇒ 空 body 被拒),**不**建出垃圾行。
#[tokio::test]
async fn empty_body_on_write_returns_the_business_envelope() {
let (app, token, _state) = build().await;
let t = token.as_str();
// 🔴 用**本用例专属**的实体(`Notification` ⇒ `tdc_notify`):
// 本测试二进制共用一个 PGlite,且 `cargo test` 并行跑用例 ⇒
// 若与 `write_routes_work_over_http` 共用 `PolicyTemplate`,
// 它的 POST 建行 / DELETE 之间的窗口会让「前后 total 对比」随机变红。
// `tdc_notify` 只有 `f_id` 是 NOT NULL 且无 DEFAULT ⇒ 空 body 原本能建出一行全 null 垃圾数据。
let (status, body) = call(&app, get("/api/ssw/tdc/Notification", Some(t))).await;
assert_eq!(status, 200);
let before = body["data"]["pagination"]["total"].as_i64().unwrap_or(0);
// POST + Content-Type: application/json + 空 body
let r = Request::builder()
.method("POST")
.uri("/api/ssw/tdc/Notification")
.header("Content-Type", "application/json")
.header("X-Internal-Token", t)
.body(Body::empty())
.unwrap();
let (status, body) = call(&app, r).await;
assert_eq!(
status, 200,
"空 body 也应是 HTTP 200 + 业务信封:{:?}",
body
);
assert_eq!(body["code"], 400, "空 body 应是业务失败:{:?}", body);
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
assert_eq!(body.get("data"), Some(&Value::Null));
// 🔴 关键:不得建出一行垃圾数据
let (status, body) = call(&app, get("/api/ssw/tdc/Notification", Some(t))).await;
assert_eq!(status, 200);
let after = body["data"]["pagination"]["total"].as_i64().unwrap_or(0);
assert_eq!(after, before, "空 body 不得建出行:{:?}", body);
}
/// 方法不允许 ⇒ JSON(不是空体)。
#[tokio::test]
async fn method_not_allowed_returns_json() {