优化了评论分页加载的列表显示
All checks were successful
Push to Helm Chart Repository / build (push) Successful in 15s

This commit is contained in:
2025-09-10 14:47:45 +08:00
parent eb66a51051
commit a7da023b1e
14 changed files with 404 additions and 294 deletions

View File

@ -6,6 +6,7 @@ import (
"strconv"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/snowykami/neo-blog/internal/ctxutils"
"github.com/snowykami/neo-blog/internal/dto"
"github.com/snowykami/neo-blog/internal/service"
@ -30,13 +31,13 @@ func (cc *CommentController) CreateComment(ctx context.Context, c *app.RequestCo
resps.BadRequest(c, err.Error())
return
}
err := cc.service.CreateComment(ctx, &req)
commentID, err := cc.service.CreateComment(ctx, &req)
if err != nil {
serviceErr := errs.AsServiceError(err)
resps.Custom(c, serviceErr.Code, serviceErr.Message, nil)
return
}
resps.Ok(c, resps.Success, nil)
resps.Ok(c, resps.Success, utils.H{"id": commentID})
}
func (cc *CommentController) UpdateComment(ctx context.Context, c *app.RequestContext) {

View File

@ -2,6 +2,9 @@ package v1
import (
"context"
"slices"
"strings"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/snowykami/neo-blog/internal/ctxutils"
@ -10,8 +13,6 @@ import (
"github.com/snowykami/neo-blog/pkg/constant"
"github.com/snowykami/neo-blog/pkg/errs"
"github.com/snowykami/neo-blog/pkg/resps"
"slices"
"strings"
)
type PostController struct {

View File

@ -69,7 +69,7 @@ func (u *UserController) Logout(ctx context.Context, c *app.RequestContext) {
ctxutils.ClearTokenAndRefreshTokenCookie(c)
resps.Ok(c, resps.Success, nil)
// 尝试吊销服务端状态:若用户登录的情况下
// TODO: 这里可以添加服务端状态的吊销逻辑
// TODO: 添加服务端状态的吊销逻辑
}
func (u *UserController) OidcList(ctx context.Context, c *app.RequestContext) {
@ -176,3 +176,11 @@ func (u *UserController) VerifyEmail(ctx context.Context, c *app.RequestContext)
}
resps.Ok(c, resps.Success, resp)
}
func (u *UserController) ChangePassword(ctx context.Context, c *app.RequestContext) {
// TODO: 实现修改密码功能
}
func (u *UserController) ChangeEmail(ctx context.Context, c *app.RequestContext) {
// TODO: 实现修改邮箱功能
}

View File

@ -1,6 +1,8 @@
package model
import "gorm.io/gorm"
import (
"gorm.io/gorm"
)
type Comment struct {
gorm.Model

View File

@ -72,13 +72,14 @@ func (cr *CommentRepo) deleteChildren(tx *gorm.DB, parentID uint) error {
return nil
}
func (cr *CommentRepo) CreateComment(comment *model.Comment) error {
func (cr *CommentRepo) CreateComment(comment *model.Comment) (uint, error) {
var commentID uint
err := GetDB().Transaction(func(tx *gorm.DB) error {
depth := 0
if comment.ReplyID != 0 {
isCircular, err := cr.isCircularReference(tx, comment.ID, comment.ReplyID)
if err != nil {
return err // 检查过程中发生数据库错误
return err
}
if isCircular {
return errs.New(http.StatusBadRequest, "circular reference detected in comment tree", nil)
@ -100,11 +101,26 @@ func (cr *CommentRepo) CreateComment(comment *model.Comment) error {
if err := tx.Create(comment).Error; err != nil {
return err
}
return nil
})
commentID = comment.ID // 记录主键
switch comment.TargetType {
case constant.TargetTypePost:
var count int64
if err := tx.Model(&model.Comment{}).
Where("target_id = ? AND target_type = ?", comment.TargetID, constant.TargetTypePost).
Count(&count).Error; err != nil {
return err
}
if err := tx.Model(&model.Post{}).Where("id = ?", comment.TargetID).
UpdateColumn("comment_count", count).Error; err != nil {
return err
}
default:
return errs.New(http.StatusBadRequest, "unsupported target type: "+comment.TargetType, nil)
}
return nil
})
return commentID, err
}
func (cr *CommentRepo) UpdateComment(comment *model.Comment) error {
if comment.ID == 0 {
return errs.New(http.StatusBadRequest, "invalid comment ID", nil)
@ -154,6 +170,23 @@ func (cr *CommentRepo) DeleteComment(commentID string) error {
}
}
// 5. 更新目标的评论数量
switch comment.TargetType {
case constant.TargetTypePost:
var count int64
if err := tx.Model(&model.Comment{}).
Where("target_id = ? AND target_type = ?", comment.TargetID, constant.TargetTypePost).
Count(&count).Error; err != nil {
return err
}
if err := tx.Model(&model.Post{}).Where("id = ?", comment.TargetID).
UpdateColumn("comment_count", count).Error; err != nil {
return err
}
default:
return errs.New(http.StatusBadRequest, "unsupported target type: "+comment.TargetType, nil)
}
return nil
})
@ -213,3 +246,12 @@ func (cr *CommentRepo) ListComments(currentUserID, targetID, commentID uint, tar
return items, nil
}
func (cr *CommentRepo) CountComments(targetType string, targetID uint) (int64, error) {
var count int64
err := GetDB().Model(&model.Comment{}).Where("target_id = ? AND target_type = ?", targetID, targetType).Count(&count).Error
if err != nil {
return 0, err
}
return count, nil
}

View File

@ -21,5 +21,7 @@ func registerUserRoutes(group *route.RouterGroup) {
userGroup.GET("/me", userController.GetUser)
userGroupWithoutAuth.POST("/logout", userController.Logout)
userGroup.PUT("/u/:id", userController.UpdateUser)
userGroup.PUT("/password/edit", userController.ChangePassword)
userGroup.PUT("/email/edit", userController.ChangeEmail)
}
}

View File

@ -19,17 +19,17 @@ func NewCommentService() *CommentService {
return &CommentService{}
}
func (cs *CommentService) CreateComment(ctx context.Context, req *dto.CreateCommentReq) error {
func (cs *CommentService) CreateComment(ctx context.Context, req *dto.CreateCommentReq) (uint, error) {
currentUser, ok := ctxutils.GetCurrentUser(ctx)
if !ok {
return errs.ErrUnauthorized
return 0, errs.ErrUnauthorized
}
if ok, err := cs.checkTargetExists(req.TargetID, req.TargetType); !ok {
if err != nil {
return errs.New(errs.ErrBadRequest.Code, "target not found", err)
return 0, errs.New(errs.ErrBadRequest.Code, "target not found", err)
}
return errs.ErrBadRequest
return 0, errs.ErrBadRequest
}
comment := &model.Comment{
@ -41,13 +41,13 @@ func (cs *CommentService) CreateComment(ctx context.Context, req *dto.CreateComm
IsPrivate: req.IsPrivate,
}
err := repo.Comment.CreateComment(comment)
commentID, err := repo.Comment.CreateComment(comment)
if err != nil {
return err
return 0, err
}
return nil
return commentID, nil
}
func (cs *CommentService) UpdateComment(ctx context.Context, req *dto.UpdateCommentReq) error {

View File

@ -20,8 +20,8 @@ export async function createComment(
replyId: number | null
isPrivate: boolean
}
): Promise<BaseResponse<Comment>> {
const res = await axiosClient.post<BaseResponse<Comment>>('/comment/c', {
): Promise<BaseResponse<{id: number}>> {
const res = await axiosClient.post<BaseResponse<{id: number}>>('/comment/c', {
targetType,
targetId,
content,
@ -52,7 +52,6 @@ export async function deleteComment({ id }: { id: number }): Promise<void> {
await axiosClient.delete(`/comment/c/${id}`)
}
export async function listComments({
targetType,
targetId,
@ -83,3 +82,8 @@ export async function listComments({
})
return res.data
}
export async function getComment({ id }: { id: number }): Promise<BaseResponse<Comment>> {
const res = await axiosClient.get<BaseResponse<Comment>>(`/comment/c/${id}`)
return res.data
}

View File

@ -5,7 +5,7 @@ import { RenderMarkdown } from "@/components/common/markdown";
import { isMobileByUA } from "@/utils/server/device";
import { calculateReadingTime } from "@/utils/common/post";
import { CommentSection } from "@/components/comment";
import { TargetType } from '../../models/types';
import { TargetType } from '@/models/types';
function PostMeta({ post }: { post: Post }) {
return (
@ -139,7 +139,7 @@ async function BlogPost({ post }: { post: Post }) {
{/* <ScrollToTop /> */}
<PostHeader post={post} />
<PostContent post={post} />
<CommentSection targetType={TargetType.Post} targetId={post.id} />
<CommentSection targetType={TargetType.Post} targetId={post.id} totalCount={post.commentCount} />
</div>
);
}

View File

@ -12,7 +12,6 @@ import { useDoubleConfirm } from "@/hooks/use-double-confirm";
import { CommentInput } from "./comment-input";
import { createComment, deleteComment, listComments, updateComment } from "@/api/comment";
import { OrderBy } from "@/models/common";
import config from "@/config";
import { formatDateTime } from "@/utils/common/datetime";
@ -23,7 +22,8 @@ export function CommentItem(
parentComment,
onCommentDelete,
activeInput,
setActiveInputId
setActiveInputId,
onReplySubmitted // 评论区计数更新用
}: {
user: User | null,
comment: Comment,
@ -31,6 +31,7 @@ export function CommentItem(
onCommentDelete: ({ commentId }: { commentId: number }) => void,
activeInput: { id: number; type: 'reply' | 'edit' } | null,
setActiveInputId: (input: { id: number; type: 'reply' | 'edit' } | null) => void,
onReplySubmitted: ({ commentContent, isPrivate }: { commentContent: string, isPrivate: boolean }) => void,
}
) {
const locale = useLocale();
@ -96,7 +97,7 @@ export function CommentItem(
orderBy: OrderBy.CreatedAt,
desc: false,
page: 1,
size: config.commentsPerPage,
size: 999999,
commentId: comment.id
}
).then(response => {
@ -136,6 +137,7 @@ export function CommentItem(
setShowReplies(true);
setActiveInputId(null);
setReplyCount(replyCount + 1);
onReplySubmitted({ commentContent, isPrivate });
}).catch(error => {
toast.error(t("comment_failed") + ": " +
error?.response?.data?.message || error?.message
@ -289,6 +291,7 @@ export function CommentItem(
onCommentDelete={onReplyDelete}
activeInput={activeInput}
setActiveInputId={setActiveInputId}
onReplySubmitted={onReplySubmitted}
/>
))}
</div>

View File

@ -5,7 +5,7 @@ import { useTranslations } from "next-intl";
import { Suspense, useEffect, useState } from "react";
import { toast } from "sonner";
import { Comment } from "@/models/comment";
import { createComment, deleteComment, listComments } from "@/api/comment";
import { createComment, deleteComment, getComment, listComments } from "@/api/comment";
import { TargetType } from "@/models/types";
import { OrderBy } from "@/models/common";
import { Separator } from "@/components/ui/separator";
@ -22,18 +22,22 @@ import "./style.css";
export function CommentSection(
{
targetType,
targetId
targetId,
totalCount = 0
}: {
targetType: TargetType,
targetId: number
targetId: number,
totalCount?: number
}
) {
const t = useTranslations('Comment')
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [comments, setComments] = useState<Comment[]>([]);
const [refreshCommentsKey, setRefreshCommentsKey] = useState(0);
const [activeInput, setActiveInput] = useState<{ id: number; type: 'reply' | 'edit' } | null>(null);
const [page, setPage] = useState(1); // 当前页码
const [totalCommentCount, setTotalCommentCount] = useState(totalCount); // 评论总数
const [needLoadMore, setNeedLoadMore] = useState(true); // 是否需要加载更多当最后一次获取的评论数小于分页大小时设为false
// 获取当前登录用户
useEffect(() => {
@ -51,13 +55,13 @@ export function CommentSection(
depth: 0,
orderBy: OrderBy.CreatedAt,
desc: true,
page: 1,
page: page,
size: config.commentsPerPage,
commentId: 0
}).then(response => {
setComments(response.data);
});
}, [refreshCommentsKey])
}, [])
const onCommentSubmitted = ({ commentContent, isPrivate }: { commentContent: string, isPrivate: boolean }) => {
createComment({
@ -66,25 +70,56 @@ export function CommentSection(
content: commentContent,
replyId: null,
isPrivate,
}).then(() => {
}).then(res => {
toast.success(t("comment_success"));
setRefreshCommentsKey(k => k + 1);
setTotalCommentCount(c => c + 1);
setComments(prevComments => prevComments.slice(0, -1));
getComment({ id: res.data.id }).then(response => {
console.log("New comment fetched:", response.data);
setComments(prevComments => [response.data, ...prevComments]);
});
setActiveInput(null);
})
}
const onReplySubmitted = ({ }: { commentContent: string, isPrivate: boolean }) => {
setTotalCommentCount(c => c + 1);
}
const onCommentDelete = ({ commentId }: { commentId: number }) => {
deleteComment({ id: commentId }).then(() => {
toast.success(t("delete_success"));
setRefreshCommentsKey(k => k + 1);
setComments(prevComments => prevComments.filter(comment => comment.id !== commentId));
setTotalCommentCount(c => c - 1);
}).catch(error => {
toast.error(t("delete_failed") + ": " + error.message);
});
}
const handleLoadMore = () => {
const nextPage = page + 1;
listComments({
targetType,
targetId,
depth: 0,
orderBy: OrderBy.CreatedAt,
desc: true,
page: nextPage,
size: config.commentsPerPage,
commentId: 0
}).then(response => {
if (response.data.length < config.commentsPerPage) {
setNeedLoadMore(false);
}
setComments(prevComments => [...prevComments, ...response.data]);
setPage(nextPage);
});
}
return (
<div>
<Separator className="my-16" />
<div className="font-bold text-2xl">{t("comment")}</div>
<div className="font-bold text-2xl">{t("comment")} ({totalCommentCount})</div>
<CommentInput
user={currentUser}
onCommentSubmitted={onCommentSubmitted}
@ -92,7 +127,7 @@ export function CommentSection(
<div className="mt-4">
<Suspense fallback={<CommentLoading />}>
{comments.map((comment, idx) => (
<div key={comment.id} className="fade-in-up" style={{ animationDelay: `${idx * 60}ms` }}>
<div key={comment.id} className="" style={{ animationDelay: `${idx * 60}ms` }}>
<Separator className="my-2" />
<CommentItem
user={currentUser}
@ -101,10 +136,20 @@ export function CommentSection(
onCommentDelete={onCommentDelete}
activeInput={activeInput}
setActiveInputId={setActiveInput}
onReplySubmitted={onReplySubmitted}
/>
</div>
))}
</Suspense>
{needLoadMore ?
<p onClick={handleLoadMore} className="text-center text-sm text-gray-500 my-4 cursor-pointer hover:underline">
{t("load_more")}
</p>
:
<p className="text-center text-sm text-gray-500 my-4">
{t("no_more")}
</p>
}
</div>
</div>
)

View File

@ -15,7 +15,7 @@ const config = {
bodyWidth: "80vw",
bodyWidthMobile: "100vw",
postsPerPage: 12,
commentsPerPage: 20,
commentsPerPage: 8,
footer: {
text: "Liteyuki ICP备 1145141919810",
links: []

View File

@ -21,7 +21,9 @@
"like": "点赞",
"like_failed": "点赞失败",
"like_success": "点赞成功",
"load_more": "加载更多",
"login_required": "请先登录后再操作",
"no_more": "没有更多了!",
"placeholder": "写下你的评论...",
"private": "私密评论",
"private_placeholder": "悄悄地说一句...",