Refactor BookRecommended function to streamline chapter recommendations. Simplify error handling and ensure consistent output format. Remove unused code related to fallback logic for chapter retrieval, enhancing performance and maintainability.

This commit is contained in:
Alex-larget
2026-03-12 11:42:13 +08:00
parent d3b67681d7
commit 41ebc70a50

View File

@@ -380,12 +380,14 @@ func BookHot(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": list})
}
// BookRecommended GET /api/book/recommended 精选推荐(首页「为你推荐」前 3 章,带 热门/推荐/精选 标签
// BookRecommended GET /api/book/recommended 精选推荐(首页「为你推荐」前 3 章)
// 与内容排行榜完全同源:使用 computeArticleRankingSections取前 3 条,保证顺序一致
func BookRecommended(c *gin.Context) {
// 优先复用管理端内容排行榜的算法,保证与后台「内容排行榜」顺序一致
sections, err := computeArticleRankingSections(database.DB())
if err == nil && len(sections) > 0 {
// 前 3 名作为精选推荐
if err != nil || len(sections) == 0 {
c.JSON(http.StatusOK, gin.H{"success": true, "data": []gin.H{}})
return
}
limit := 3
if len(sections) < limit {
limit = len(sections)
@@ -411,33 +413,6 @@ func BookRecommended(c *gin.Context) {
})
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
return
}
// 兜底:沿用原有热门章节算法,至少保证有推荐
list := bookHotChaptersSorted(database.DB(), 3)
if len(list) == 0 {
// 第二层兜底:按 updated_at 取前 3同样排除序言/尾声/附录
q := database.DB().Model(&model.Chapter{})
for _, p := range excludeParts {
q = q.Where("part_title NOT LIKE ?", "%"+p+"%")
}
q.Order("updated_at DESC, id ASC").Limit(3).Find(&list)
}
tags := []string{"热门", "推荐", "精选"}
out := make([]gin.H, 0, len(list))
for i, ch := range list {
tag := "精选"
if i < len(tags) {
tag = tags[i]
}
out = append(out, gin.H{
"id": ch.ID, "mid": ch.MID, "sectionTitle": ch.SectionTitle, "partTitle": ch.PartTitle,
"chapterTitle": ch.ChapterTitle, "tag": tag,
"isFree": ch.IsFree, "price": ch.Price, "isNew": ch.IsNew,
})
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
}
// BookLatestChapters GET /api/book/latest-chapters