完整新闻信息管理
This commit is contained in:
@@ -4,23 +4,40 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/logic/article"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/model"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
)
|
||||
|
||||
func CreateArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
func CreateArticleHandler(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req types.CreateArticleReq
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
mysqlCfg := cfg.MySQL
|
||||
dsn := fmt.Sprintf(
|
||||
"%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true&loc=Local",
|
||||
mysqlCfg.Username,
|
||||
mysqlCfg.Password,
|
||||
mysqlCfg.Host,
|
||||
mysqlCfg.Port,
|
||||
mysqlCfg.Database,
|
||||
mysqlCfg.Charset,
|
||||
)
|
||||
fmt.Println("接收到articlePost请求")
|
||||
|
||||
l := article.NewCreateArticleLogic(r.Context(), svcCtx)
|
||||
conn := sqlx.NewSqlConn("mysql", dsn)
|
||||
articleModel := model.NewArticleModel(conn)
|
||||
|
||||
l := article.NewCreateArticleLogic(r.Context(), cfg, articleModel)
|
||||
resp, err := l.CreateArticle(&req)
|
||||
if err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
@@ -6,13 +6,13 @@ package article
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/logic/article"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
)
|
||||
|
||||
func DeleteArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
func DeleteArticleHandler(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req types.DeleteArticleReq
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
@@ -20,7 +20,7 @@ func DeleteArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
l := article.NewDeleteArticleLogic(r.Context(), svcCtx)
|
||||
l := article.NewDeleteArticleLogic(r.Context(), cfg)
|
||||
resp, err := l.DeleteArticle(&req)
|
||||
if err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
@@ -6,13 +6,13 @@ package article
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/logic/article"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
)
|
||||
|
||||
func DetailArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
func DetailArticleHandler(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req types.DetailArticleReq
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
@@ -20,7 +20,7 @@ func DetailArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
l := article.NewDetailArticleLogic(r.Context(), svcCtx)
|
||||
l := article.NewDetailArticleLogic(r.Context(), cfg)
|
||||
resp, err := l.DetailArticle(&req)
|
||||
if err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
@@ -4,15 +4,18 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/logic/article"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/model"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
)
|
||||
|
||||
func ListArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
func ListArticleHandler(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req types.ListArticleReq
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
@@ -20,7 +23,22 @@ func ListArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
l := article.NewListArticleLogic(r.Context(), svcCtx)
|
||||
mysqlCfg := cfg.MySQL
|
||||
dsn := fmt.Sprintf(
|
||||
"%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true&loc=Local",
|
||||
mysqlCfg.Username,
|
||||
mysqlCfg.Password,
|
||||
mysqlCfg.Host,
|
||||
mysqlCfg.Port,
|
||||
mysqlCfg.Database,
|
||||
mysqlCfg.Charset,
|
||||
)
|
||||
fmt.Println("接收到articlePost请求")
|
||||
|
||||
conn := sqlx.NewSqlConn("mysql", dsn)
|
||||
articleModel := model.NewArticleModel(conn)
|
||||
|
||||
l := article.NewListArticleLogic(r.Context(), cfg, articleModel)
|
||||
resp, err := l.ListArticle(&req)
|
||||
if err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
@@ -6,13 +6,13 @@ package article
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/logic/article"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
)
|
||||
|
||||
func UpdateArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
func UpdateArticleHandler(cfg *config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req types.UpdateArticleReq
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
@@ -20,7 +20,7 @@ func UpdateArticleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
l := article.NewUpdateArticleLogic(r.Context(), svcCtx)
|
||||
l := article.NewUpdateArticleLogic(r.Context(), cfg)
|
||||
resp, err := l.UpdateArticle(&req)
|
||||
if err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
@@ -5,8 +5,12 @@ package article
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/model"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
@@ -14,20 +18,98 @@ import (
|
||||
|
||||
type CreateArticleLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
model model.ArticleModel
|
||||
}
|
||||
|
||||
func NewCreateArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateArticleLogic {
|
||||
func NewCreateArticleLogic(ctx context.Context, cfg *config.Config, model model.ArticleModel) *CreateArticleLogic {
|
||||
return &CreateArticleLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
cfg: cfg,
|
||||
model: model,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateArticleLogic) CreateArticle(req *types.CreateArticleReq) (resp *types.CreateArticleResp, err error) {
|
||||
// todo: add your logic here and delete this line
|
||||
ctxLog := logx.WithContext(l.ctx)
|
||||
|
||||
return
|
||||
// 标题不能为空,且长度建议限制(避免过长)
|
||||
if req.Title == "" {
|
||||
// 用 Info 替代 Warn,添加 [WARN] 标识
|
||||
ctxLog.Info("[WARN] 文章标题不能为空")
|
||||
return nil, fmt.Errorf("文章标题不能为空")
|
||||
}
|
||||
if len(req.Title) > 100 { // 假设标题最大100字符,可根据需求调整
|
||||
// 用 Infof 替代 Warnf,添加 [WARN] 标识
|
||||
ctxLog.Infof("[WARN] 文章标题过长,当前长度:%d,最大允许:100", len(req.Title))
|
||||
return nil, fmt.Errorf("文章标题不能超过100个字符")
|
||||
}
|
||||
|
||||
// 内容不能为空(核心字段)
|
||||
if req.Content == "" {
|
||||
ctxLog.Info("[WARN] 文章内容不能为空")
|
||||
return nil, fmt.Errorf("文章内容不能为空")
|
||||
}
|
||||
|
||||
// 可选:封面图、话题字段的基础校验(如封面图URL格式,话题长度)
|
||||
if req.Cover != "" && !strings.HasPrefix(req.Cover, "http") {
|
||||
// 直接用 l.Infof(结构体嵌入 logx.Logger,可直接调用)
|
||||
l.Infof("[WARN] 封面图URL格式非法:%s", req.Cover)
|
||||
return nil, fmt.Errorf("封面图URL必须以http/https开头")
|
||||
}
|
||||
if req.Topic != "" && len(req.Topic) > 50 {
|
||||
l.Infof("[WARN] 话题过长,当前长度:%d,最大允许:50", len(req.Topic))
|
||||
return nil, fmt.Errorf("话题不能超过50个字符")
|
||||
}
|
||||
|
||||
// 2. 第二步:转换请求参数 → Model层的Article实体(补充缺失字段)
|
||||
// CreateArticleReq 缺失的字段(Excerpt/IsDelete/CreateAt/UpdateAt/Id)需在Logic层补充
|
||||
articleData := &model.Article{
|
||||
Title: req.Title, // 直接从请求获取
|
||||
Content: req.Content, // 直接从请求获取
|
||||
Cover: req.Cover, // 直接从请求获取(为空则存空字符串)
|
||||
Topic: req.Topic, // 直接从请求获取(为空则存空字符串)
|
||||
Excerpt: l.getExcerpt(req.Content), // 自动生成摘要(下方实现辅助函数)
|
||||
IsDelete: 0, // 默认0(未删除,1为已删除,符合数据库设计)
|
||||
CreateAt: time.Now(), // 创建时间:当前时间(或用数据库默认值,此处显式赋值更可控)
|
||||
UpdateAt: time.Now(), // 更新时间:初始与创建时间一致
|
||||
}
|
||||
|
||||
// 3. 第三步:调用Model层Insert方法,插入数据到数据库
|
||||
// 传入上下文(用于超时控制、链路追踪)和Article实体
|
||||
insertResult, err := l.model.Insert(l.ctx, articleData)
|
||||
if err != nil {
|
||||
// 记录错误日志(包含上下文信息,方便排查)
|
||||
l.Logger.Errorf("插入文章到数据库失败,标题:%s,错误:%v", req.Title, err)
|
||||
return nil, fmt.Errorf("创建文章失败,请稍后重试") // 返回用户友好错误,隐藏底层细节
|
||||
}
|
||||
|
||||
// 4. 第四步:处理Insert结果,获取自增Id(关键:响应需返回新文章的Id)
|
||||
// 若数据库Id是自增字段,通过insertResult.LastInsertId()获取新生成的Id
|
||||
newArticleId, err := insertResult.LastInsertId()
|
||||
if err != nil {
|
||||
l.Logger.Errorf("获取新文章Id失败,标题:%s,错误:%v", req.Title, err)
|
||||
return nil, fmt.Errorf("创建文章成功,但获取文章Id失败") // 特殊场景:插入成功但Id获取失败
|
||||
}
|
||||
|
||||
// 5. 第五步:构造响应结果(匹配types.CreateArticleResp结构)
|
||||
resp = &types.CreateArticleResp{
|
||||
Id: newArticleId, // 返回数据库生成的自增Id
|
||||
Success: true, // 标记创建成功
|
||||
// 可选:补充更多响应字段,如"Message": "文章创建成功"(若Resp结构体支持)
|
||||
}
|
||||
|
||||
l.Logger.Infof("文章创建成功,Id:%d,标题:%s", newArticleId, req.Title) // 记录成功日志
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (l *CreateArticleLogic) getExcerpt(content string) string {
|
||||
// 规则1:内容长度<=200字符,直接返回完整内容作为摘要
|
||||
if len(content) <= 30 {
|
||||
return content
|
||||
}
|
||||
// 规则2:内容过长,截取前200字符并加上"..."(避免截断单词,可优化为按句子截断)
|
||||
return strings.TrimSpace(content[:30]) + "..."
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ package article
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
@@ -14,15 +14,15 @@ import (
|
||||
|
||||
type DeleteArticleLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewDeleteArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteArticleLogic {
|
||||
func NewDeleteArticleLogic(ctx context.Context, cfg *config.Config) *DeleteArticleLogic {
|
||||
return &DeleteArticleLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ package article
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
@@ -14,15 +14,15 @@ import (
|
||||
|
||||
type DetailArticleLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewDetailArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DetailArticleLogic {
|
||||
func NewDetailArticleLogic(ctx context.Context, cfg *config.Config) *DetailArticleLogic {
|
||||
return &DetailArticleLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,11 @@ package article
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/model"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
@@ -14,20 +17,87 @@ import (
|
||||
|
||||
type ListArticleLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
model model.ArticleModel
|
||||
}
|
||||
|
||||
func NewListArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListArticleLogic {
|
||||
func NewListArticleLogic(ctx context.Context, cfg *config.Config, model model.ArticleModel) *ListArticleLogic {
|
||||
return &ListArticleLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
cfg: cfg,
|
||||
model: model,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ListArticleLogic) ListArticle(req *types.ListArticleReq) (resp *types.ListArticleResp, err error) {
|
||||
// todo: add your logic here and delete this line
|
||||
// 1. 处理请求参数默认值 + 合法性校验(原有逻辑保留)
|
||||
page := req.Page
|
||||
if page < 1 {
|
||||
page = 1
|
||||
l.Infof("请求页码非法(%d),自动调整为 1", req.Page)
|
||||
}
|
||||
|
||||
return
|
||||
size := req.Size
|
||||
switch {
|
||||
case size < 1:
|
||||
size = 10
|
||||
l.Infof("请求条数非法(%d),自动调整为 10", req.Size)
|
||||
case size > 100:
|
||||
size = 100
|
||||
l.Infof("请求条数过大(%d),自动限制为 100", req.Size)
|
||||
}
|
||||
|
||||
topic := req.Topic
|
||||
|
||||
// 2. 修正:按接口定义接收 3 个返回值(列表、总条数、错误)
|
||||
// 原错误:只接收了 2 个返回值,缺少“总条数”
|
||||
articleList, total, err := l.model.List(l.ctx, page, size, topic)
|
||||
if err != nil {
|
||||
l.Errorf("Model 层查询文章列表失败:topic=%s, page=%d, size=%d, 错误:%v", topic, page, size, err)
|
||||
return nil, fmt.Errorf("获取文章列表失败,请稍后重试")
|
||||
}
|
||||
|
||||
// 3. 计算总页数(接口只返回总条数,总页数需在 Logic 层计算)
|
||||
// 向上取整公式:(总条数 + 每页条数 - 1) / 每页条数(避免浮点数误差)
|
||||
var totalPage int64
|
||||
if total > 0 {
|
||||
totalPage = (total + int64(size) - 1) / int64(size)
|
||||
} else {
|
||||
totalPage = 0 // 总条数为 0 时,总页数也为 0
|
||||
}
|
||||
|
||||
// 4. 结构转换:Model.Article → Types.ArticleItem(适配前端)
|
||||
var articleItems []types.Article
|
||||
for _, art := range articleList {
|
||||
// 注意:art 是 *Article 指针,取值时用 *art
|
||||
articleItems = append(articleItems, types.Article{
|
||||
Id: art.Id,
|
||||
Title: art.Title,
|
||||
Cover: art.Cover,
|
||||
Topic: art.Topic,
|
||||
Excerpt: art.Excerpt,
|
||||
Content: art.Content,
|
||||
// 时间格式化:转为本地时间字符串
|
||||
CreateAt: art.CreateAt.In(time.Local).Format("2006-01-02 15:04:05"),
|
||||
UpdateAt: art.UpdateAt.In(time.Local).Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// 5. 组装前端所需的响应结构
|
||||
resp = &types.ListArticleResp{
|
||||
Total: total, // 总条数(来自 Model 层返回)
|
||||
TotalPage: totalPage, // 计算出的总页数
|
||||
List: articleItems, // 转换后的前端列表
|
||||
Page: page, // 当前页码(处理后的有效值)
|
||||
Size: size, // 每页条数(处理后的有效值)
|
||||
}
|
||||
for i, item := range resp.List {
|
||||
fmt.Printf("[DEBUG] 响应第 %d 条文章的 Content:%q\n", i+1, item.Content)
|
||||
}
|
||||
|
||||
l.Infof("文章列表查询成功:topic=%s, page=%d, size=%d, 总条数=%d, 总页数=%d",
|
||||
topic, page, size, total, totalPage)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ package article
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/svc"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/config"
|
||||
"github.com/JACKYMYPERSON/hldrCenter/internal/article/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
@@ -14,15 +14,15 @@ import (
|
||||
|
||||
type UpdateArticleLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewUpdateArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateArticleLogic {
|
||||
func NewUpdateArticleLogic(ctx context.Context, cfg *config.Config) *UpdateArticleLogic {
|
||||
return &UpdateArticleLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,14 +13,14 @@ type (
|
||||
}
|
||||
|
||||
customArticleModel struct {
|
||||
*defaultArticleModel
|
||||
*DefaultArticleModel
|
||||
}
|
||||
)
|
||||
|
||||
// NewArticleModel returns a model for the database table.
|
||||
func NewArticleModel(conn sqlx.SqlConn) ArticleModel {
|
||||
return &customArticleModel{
|
||||
defaultArticleModel: newArticleModel(conn),
|
||||
DefaultArticleModel: newArticleModel(conn),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +19,22 @@ import (
|
||||
var (
|
||||
articleFieldNames = builder.RawFieldNames(&Article{})
|
||||
articleRows = strings.Join(articleFieldNames, ",")
|
||||
articleRowsExpectAutoSet = strings.Join(stringx.Remove(articleFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",")
|
||||
articleRowsExpectAutoSet = strings.Join(stringx.Remove(articleFieldNames, "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`","`id`"), ",")
|
||||
articleRowsWithPlaceHolder = strings.Join(stringx.Remove(articleFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?"
|
||||
articleListFields = strings.Join(
|
||||
[]string{
|
||||
"`id`", // 1. 对应 id
|
||||
"`title`", // 2. 对应 title
|
||||
"`content`", // 3. 🔥 新增:查询 content 字段
|
||||
"`cover`", // 4. 对应 cover
|
||||
"`topic`", // 5. 对应 topic
|
||||
"`excerpt`", // 6. 对应 excerpt
|
||||
"`create_at`", // 7. 对应 create_at
|
||||
"`update_at`", // 8. 对应 update_at
|
||||
"`is_delete`", // 9. 对应 is_delete
|
||||
},
|
||||
",",
|
||||
)
|
||||
)
|
||||
|
||||
type (
|
||||
@@ -29,9 +43,10 @@ type (
|
||||
FindOne(ctx context.Context, id int64) (*Article, error)
|
||||
Update(ctx context.Context, data *Article) error
|
||||
Delete(ctx context.Context, id int64) error
|
||||
List(ctx context.Context, page, size int, topic string) ([]*Article, int64, error)
|
||||
}
|
||||
|
||||
defaultArticleModel struct {
|
||||
DefaultArticleModel struct {
|
||||
conn sqlx.SqlConn
|
||||
table string
|
||||
}
|
||||
@@ -47,22 +62,35 @@ type (
|
||||
Excerpt string `db:"excerpt"`
|
||||
Id int64 `db:"id"`
|
||||
}
|
||||
|
||||
articleListItem struct {
|
||||
Id int64 `db:"id"` // 与 articleListFields 第1个字段对应
|
||||
Title string `db:"title"` // 与第2个字段对应
|
||||
Content string `db:"content"` // 🔥 新增:与第3个字段(content)对应
|
||||
Cover string `db:"cover"` // 与第4个字段对应
|
||||
Topic string `db:"topic"` // 与第5个字段对应
|
||||
Excerpt string `db:"excerpt"` // 与第6个字段对应
|
||||
CreateAt time.Time `db:"create_at"` // 与第7个字段对应
|
||||
UpdateAt time.Time `db:"update_at"` // 与第8个字段对应
|
||||
IsDelete int64 `db:"is_delete"` // 与第9个字段对应
|
||||
}
|
||||
|
||||
)
|
||||
|
||||
func newArticleModel(conn sqlx.SqlConn) *defaultArticleModel {
|
||||
return &defaultArticleModel{
|
||||
func newArticleModel(conn sqlx.SqlConn) *DefaultArticleModel {
|
||||
return &DefaultArticleModel{
|
||||
conn: conn,
|
||||
table: "`article`",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultArticleModel) Delete(ctx context.Context, id int64) error {
|
||||
func (m *DefaultArticleModel) Delete(ctx context.Context, id int64) error {
|
||||
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
|
||||
_, err := m.conn.ExecCtx(ctx, query, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultArticleModel) FindOne(ctx context.Context, id int64) (*Article, error) {
|
||||
func (m *DefaultArticleModel) FindOne(ctx context.Context, id int64) (*Article, error) {
|
||||
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", articleRows, m.table)
|
||||
var resp Article
|
||||
err := m.conn.QueryRowCtx(ctx, &resp, query, id)
|
||||
@@ -76,18 +104,99 @@ func (m *defaultArticleModel) FindOne(ctx context.Context, id int64) (*Article,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *defaultArticleModel) Insert(ctx context.Context, data *Article) (sql.Result, error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?)", m.table, articleRowsExpectAutoSet)
|
||||
ret, err := m.conn.ExecCtx(ctx, query, data.Title, data.Content, data.Cover, data.IsDelete, data.Topic, data.Excerpt, data.Id)
|
||||
func (m *DefaultArticleModel) Insert(ctx context.Context, data *Article) (sql.Result, error) {
|
||||
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, articleRowsExpectAutoSet)
|
||||
ret, err := m.conn.ExecCtx(ctx, query, data.Title, data.Content, data.Cover, data.IsDelete, data.Topic, data.Excerpt)
|
||||
return ret, err
|
||||
}
|
||||
|
||||
func (m *defaultArticleModel) Update(ctx context.Context, data *Article) error {
|
||||
func (m *DefaultArticleModel) Update(ctx context.Context, data *Article) error {
|
||||
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, articleRowsWithPlaceHolder)
|
||||
fmt.Println("Insert SQL 字段列表:", articleRowsExpectAutoSet)
|
||||
_, err := m.conn.ExecCtx(ctx, query, data.Title, data.Content, data.Cover, data.IsDelete, data.Topic, data.Excerpt, data.Id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *defaultArticleModel) tableName() string {
|
||||
|
||||
func (m *DefaultArticleModel) List(ctx context.Context, page, size int, topic string) ([]*Article, int64, error) {
|
||||
// 1. 统计符合条件的总条数(只查未删除数据)
|
||||
var countBuilder strings.Builder
|
||||
countBuilder.WriteString(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `is_delete` = 0", m.table))
|
||||
|
||||
var args []interface{}
|
||||
// 动态添加话题筛选条件(topic 非空才加)
|
||||
if topic != "" {
|
||||
countBuilder.WriteString(" AND `topic` = ?")
|
||||
args = append(args, topic)
|
||||
}
|
||||
|
||||
// 执行总条数查询(go-zero 正确参数顺序:ctx → &total → query → args...)
|
||||
var total int64
|
||||
countSql := countBuilder.String()
|
||||
err := m.conn.QueryRowCtx(ctx, &total, countSql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("统计总条数失败:sql=%s, args=%v, err=%v", countSql, args, err)
|
||||
}
|
||||
|
||||
// 空数据优化:总条数为 0 时,直接返回空列表(避免后续无效查询)
|
||||
if total == 0 {
|
||||
return []*Article{}, 0, nil
|
||||
}
|
||||
|
||||
// 2. 分页查询列表数据(包含 content 字段)
|
||||
var listBuilder strings.Builder
|
||||
// 关键:使用包含 content 的 articleListFields,SQL 会查询 content
|
||||
listBuilder.WriteString(fmt.Sprintf("SELECT %s FROM %s WHERE `is_delete` = 0", articleListFields, m.table))
|
||||
|
||||
// 复用话题筛选条件(与总条数查询条件一致,确保数据一致性)
|
||||
if topic != "" {
|
||||
listBuilder.WriteString(" AND `topic` = ?")
|
||||
}
|
||||
|
||||
// 分页计算(页码从 1 开始,OFFSET = (page-1)*size,避免负偏移)
|
||||
offset := (page - 1) * size
|
||||
listBuilder.WriteString(" ORDER BY `create_at` DESC LIMIT ? OFFSET ?")
|
||||
// 追加分页参数(顺序:先 LIMIT size,再 OFFSET offset)
|
||||
listArgs := append(args, size, offset)
|
||||
|
||||
// 3. 扫描到临时结构体(articleListItem 包含 content,避免直接扫描大字段到 Article)
|
||||
var tempList []*articleListItem
|
||||
listSql := listBuilder.String()
|
||||
// go-zero 正确调用:ctx → &tempList → query → listArgs...(args 需加 ... 展开)
|
||||
err = m.conn.QueryRowsCtx(ctx, &tempList, listSql, listArgs...)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("查询列表失败:sql=%s, args=%v, err=%v", listSql, listArgs, err)
|
||||
}
|
||||
|
||||
// 4. 转换为业务层需要的 Article 切片(关键:赋值 Content 字段)
|
||||
articleList := make([]*Article, 0, len(tempList))
|
||||
for _, item := range tempList {
|
||||
|
||||
fmt.Printf("[DEBUG] 扫描到的文章ID:%d,Content值:%q\n", item.Id, item.Content)
|
||||
// 打印 SQL 实际查询的字段,确认 content 存在
|
||||
fmt.Printf("[DEBUG] SQL 查询字段:%s\n", articleListFields)
|
||||
articleList = append(articleList, &Article{
|
||||
Id: item.Id, // 主键
|
||||
Title: item.Title, // 标题
|
||||
Content: item.Content, // 🔥 核心:赋值 content(解决为空问题)
|
||||
Cover: item.Cover, // 封面
|
||||
Topic: item.Topic, // 话题
|
||||
Excerpt: item.Excerpt, // 摘要
|
||||
CreateAt: item.CreateAt, // 创建时间
|
||||
UpdateAt: item.UpdateAt, // 更新时间
|
||||
IsDelete: item.IsDelete, // 软删除状态
|
||||
})
|
||||
}
|
||||
for i, item := range articleList {
|
||||
fmt.Printf("[DEBUG] 响应第 %d 条文章的 Content:%q\n", i+1, item.Content)
|
||||
}
|
||||
|
||||
|
||||
// 5. 返回结果(Article 切片+总条数+无错误)
|
||||
return articleList, total, nil
|
||||
}
|
||||
|
||||
|
||||
func (m *DefaultArticleModel) tableName() string {
|
||||
return m.table
|
||||
}
|
||||
|
||||
@@ -51,8 +51,11 @@ type ListArticleReq struct {
|
||||
}
|
||||
|
||||
type ListArticleResp struct {
|
||||
Total int64 `json:"total"` // 总条数
|
||||
List []Article `json:"list"` // 文章列表
|
||||
Total int64 `json:"total"` // 符合条件的总文章数(原字段保留)
|
||||
TotalPage int64 `json:"total_page"` // 新增:总页数(前端直接显示)
|
||||
List []Article `json:"Article_list"` // 当前页文章列表(原字段保留)
|
||||
Page int `json:"page"` // 当前页码(原字段保留)
|
||||
Size int `json:"size"` // 每页条数(原字段保留)
|
||||
}
|
||||
|
||||
type UpdateArticleReq struct {
|
||||
|
||||
Reference in New Issue
Block a user