feat(admin): 后台新增条目与分组 CRUD
- POST /api/items + DELETE /api/items/{key}:新增应用/海报/图文,按分区/分组挂载;PATCH 支持 nodeKey 移动
- 分组 CRUD:POST /api/categories/{id}/groups、PATCH/DELETE /api/groups/{id}(删除级联组内条目)
- PATCH /api/categories/{id} 增加 blockNodeKey,首页卡片可选择预览分组
- /admin 新增「内容」Tab(新增/删除条目),「分区」Tab 内联分组管理与卡片预览
- 测试 59 passed(条目创建/移动/删除、分组增删改)
This commit is contained in:
+232
-4
@@ -53,6 +53,18 @@ pub struct EntryPatch {
|
||||
pub body: String,
|
||||
#[serde(default)]
|
||||
pub tags: Vec<String>,
|
||||
/// 可选:把条目移动到另一个分区 / 分组(不传则保持原位)
|
||||
#[serde(default)]
|
||||
pub node_key: Option<String>,
|
||||
}
|
||||
|
||||
/// 新建条目的请求体:`key` 是业务键,`nodeKey` 决定挂在哪个分区 / 分组。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NewEntry {
|
||||
pub key: String,
|
||||
pub node_key: String,
|
||||
pub item: EntryPatch,
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
@@ -210,9 +222,150 @@ pub fn load(conn: &Connection, key: &str) -> Result<Option<EntryRecord>, StashEr
|
||||
Ok(Some(entry))
|
||||
}
|
||||
|
||||
/// 条目能挂到哪:非应用分区本身,或应用分区下的分组。
|
||||
fn validate_target(conn: &Connection, node_key: &str) -> Result<(), StashError> {
|
||||
let row: Option<(String, Option<String>, Option<String>)> = conn
|
||||
.query_row(
|
||||
"SELECT n.kind, n.view_mode, p.view_mode
|
||||
FROM node n LEFT JOIN node p ON p.key = n.parent_key
|
||||
WHERE n.key = ?1",
|
||||
[node_key],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)
|
||||
.optional()
|
||||
.map_err(map_error)?;
|
||||
|
||||
let Some((kind, view_mode, parent_mode)) = row else {
|
||||
return Err(StashError::NotFound(format!("节点不存在: {node_key}")));
|
||||
};
|
||||
|
||||
match kind.as_str() {
|
||||
"group" if parent_mode.as_deref() == Some("apps") => Ok(()),
|
||||
"group" => Err(StashError::InvalidDirectory(
|
||||
"分组只能挂在应用类分区下".into(),
|
||||
)),
|
||||
"section" if view_mode.as_deref() == Some("apps") => Err(StashError::InvalidDirectory(
|
||||
"应用类条目必须选择一个分组".into(),
|
||||
)),
|
||||
"section" => Ok(()),
|
||||
_ => Err(StashError::InvalidDirectory(
|
||||
"条目只能挂在分区或分组下".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_key(key: &str) -> bool {
|
||||
!key.is_empty()
|
||||
&& key.len() <= 64
|
||||
&& key
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-')
|
||||
}
|
||||
|
||||
fn write_tags(conn: &Connection, key: &str, tags: &[String]) -> Result<(), StashError> {
|
||||
conn.execute("DELETE FROM entry_tag WHERE entry_key = ?1", [key])
|
||||
.map_err(map_error)?;
|
||||
for (index, tag) in tags.iter().enumerate() {
|
||||
conn.execute(
|
||||
"INSERT INTO entry_tag (entry_key, sort, label) VALUES (?1, ?2, ?3)",
|
||||
params![key, index as i64, tag],
|
||||
)
|
||||
.map_err(map_error)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 新建条目:用于后台「内容」页添加网址 / 海报 / 图文。
|
||||
pub fn create(conn: &mut Connection, new: NewEntry) -> Result<EntryRecord, StashError> {
|
||||
let key = new.key.trim().to_string();
|
||||
if !valid_key(&key) {
|
||||
return Err(StashError::InvalidDirectory(
|
||||
"标识只能用小写字母、数字与连字符(≤64)".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let patch = new.item;
|
||||
validate(&patch)?;
|
||||
let href = normalize_href(&patch.href)?;
|
||||
validate_target(conn, &new.node_key)?;
|
||||
|
||||
let exists: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM entry WHERE key = ?1", [&key], |row| {
|
||||
row.get(0)
|
||||
})
|
||||
.map_err(map_error)?;
|
||||
if exists > 0 {
|
||||
return Err(StashError::Conflict(format!("条目已存在: {key}")));
|
||||
}
|
||||
|
||||
let tags: Vec<String> = patch
|
||||
.tags
|
||||
.iter()
|
||||
.map(|tag| tag.trim().to_string())
|
||||
.filter(|tag| !tag.is_empty())
|
||||
.collect();
|
||||
|
||||
let timestamp = now();
|
||||
let tx = conn.transaction().map_err(map_error)?;
|
||||
|
||||
let sort: i64 = tx
|
||||
.query_row(
|
||||
"SELECT COALESCE(MAX(sort), 0) + 1 FROM entry WHERE node_key = ?1",
|
||||
[&new.node_key],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(map_error)?;
|
||||
|
||||
tx.execute(
|
||||
"INSERT INTO entry (key, node_key, name, description, icon, href, cover, banner,
|
||||
badge, comment, summary, body, hot, views, likes, sort, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, 0, 0, 0, ?13, ?14)",
|
||||
params![
|
||||
key,
|
||||
new.node_key,
|
||||
patch.name.trim(),
|
||||
patch.description,
|
||||
patch.icon,
|
||||
href,
|
||||
patch.cover,
|
||||
patch.banner,
|
||||
patch.badge,
|
||||
patch.comment,
|
||||
patch.summary,
|
||||
patch.body,
|
||||
sort,
|
||||
timestamp
|
||||
],
|
||||
)
|
||||
.map_err(map_error)?;
|
||||
|
||||
write_tags(&tx, &key, &tags)?;
|
||||
tx.execute(
|
||||
"INSERT INTO audit (at, action, target, detail) VALUES (?1, 'item.create', ?2, ?3)",
|
||||
params![timestamp, key, patch.name.trim()],
|
||||
)
|
||||
.map_err(map_error)?;
|
||||
|
||||
tx.commit().map_err(map_error)?;
|
||||
load(conn, &key)?
|
||||
.ok_or_else(|| StashError::NotFound(format!("条目不存在: {key}")))
|
||||
}
|
||||
|
||||
/// 删除条目(后台内容页用)。
|
||||
pub fn remove(conn: &Connection, key: &str) -> Result<(), StashError> {
|
||||
let removed = conn
|
||||
.execute("DELETE FROM entry WHERE key = ?1", [key])
|
||||
.map_err(map_error)?;
|
||||
if removed == 0 {
|
||||
return Err(StashError::NotFound(format!("条目不存在: {key}")));
|
||||
}
|
||||
|
||||
audit(conn, "item.delete", key, "")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 更新条目;`expected_updated_at` 与库里不一致时冲突。
|
||||
pub fn update(
|
||||
conn: &mut Connection,
|
||||
pub fn update( conn: &mut Connection,
|
||||
key: &str,
|
||||
patch: EntryPatch,
|
||||
expected_updated_at: i64,
|
||||
@@ -220,6 +373,9 @@ pub fn update(
|
||||
validate(&patch)?;
|
||||
// 跳转地址先规范化:补 https、拒绝 javascript: 等危险协议
|
||||
let href = normalize_href(&patch.href)?;
|
||||
if let Some(node_key) = patch.node_key.as_deref() {
|
||||
validate_target(conn, node_key)?;
|
||||
}
|
||||
|
||||
let tags: Vec<String> = patch
|
||||
.tags
|
||||
@@ -236,7 +392,8 @@ pub fn update(
|
||||
"UPDATE entry SET
|
||||
name = ?1, description = ?2, icon = ?3, href = ?4,
|
||||
cover = ?5, banner = ?6, badge = ?7, comment = ?8,
|
||||
summary = ?9, body = ?10, updated_at = ?11
|
||||
summary = ?9, body = ?10, updated_at = ?11,
|
||||
node_key = COALESCE(?14, node_key)
|
||||
WHERE key = ?12 AND updated_at = ?13",
|
||||
params![
|
||||
patch.name.trim(),
|
||||
@@ -251,7 +408,8 @@ pub fn update(
|
||||
patch.body,
|
||||
timestamp,
|
||||
key,
|
||||
expected_updated_at
|
||||
expected_updated_at,
|
||||
patch.node_key
|
||||
],
|
||||
)
|
||||
.map_err(map_error)?;
|
||||
@@ -351,6 +509,17 @@ mod tests {
|
||||
target TEXT,
|
||||
detail TEXT
|
||||
);
|
||||
CREATE TABLE node (
|
||||
key TEXT PRIMARY KEY,
|
||||
parent_key TEXT,
|
||||
title TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
view_mode TEXT
|
||||
);
|
||||
INSERT INTO node (key, parent_key, title, kind, view_mode) VALUES
|
||||
('movie', NULL, '推荐电影', 'section', 'posters'),
|
||||
('apps1', NULL, '常用推荐', 'section', 'apps'),
|
||||
('g1', 'apps1', '常用站点', 'group', NULL);
|
||||
INSERT INTO entry (key, node_key, name, updated_at) VALUES ('movie-1', 'movie', '千与千寻', 0);",
|
||||
)
|
||||
.expect("应能建表");
|
||||
@@ -370,6 +539,7 @@ mod tests {
|
||||
summary: "正文".into(),
|
||||
body: "## 标题".into(),
|
||||
tags: vec!["推荐电影".into(), "动画".into()],
|
||||
node_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -440,4 +610,62 @@ mod tests {
|
||||
let saved = update(&mut conn, "movie-1", input, 0).expect("应能更新");
|
||||
assert_eq!(saved.href, "https://www.zhihu.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_entry_under_section_or_group() {
|
||||
let mut conn = db();
|
||||
let saved = create(
|
||||
&mut conn,
|
||||
NewEntry {
|
||||
key: "new-site".into(),
|
||||
node_key: "g1".into(),
|
||||
item: patch("新站点"),
|
||||
},
|
||||
)
|
||||
.expect("应能创建");
|
||||
assert_eq!(saved.key, "new-site");
|
||||
assert_eq!(saved.name, "新站点");
|
||||
|
||||
let node: String = conn
|
||||
.query_row("SELECT node_key FROM entry WHERE key='new-site'", [], |row| {
|
||||
row.get(0)
|
||||
})
|
||||
.expect("应能查");
|
||||
assert_eq!(node, "g1");
|
||||
|
||||
// 应用分区不能直接挂条目,必须先选分组
|
||||
assert!(
|
||||
create(
|
||||
&mut conn,
|
||||
NewEntry {
|
||||
key: "bad-site".into(),
|
||||
node_key: "apps1".into(),
|
||||
item: patch("错误"),
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moves_entry_between_nodes() {
|
||||
let mut conn = db();
|
||||
let mut input = patch("搬家");
|
||||
input.node_key = Some("g1".into());
|
||||
update(&mut conn, "movie-1", input, 0).expect("应能移动");
|
||||
|
||||
let node: String = conn
|
||||
.query_row("SELECT node_key FROM entry WHERE key='movie-1'", [], |row| {
|
||||
row.get(0)
|
||||
})
|
||||
.expect("应能查");
|
||||
assert_eq!(node, "g1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletes_entry() {
|
||||
let conn = db();
|
||||
remove(&conn, "movie-1").expect("应能删除");
|
||||
assert!(remove(&conn, "movie-1").is_err(), "重复删除应失败");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user