首次提交:姜十三论坛
后端 Go+Gin:认证/CSRF/限流、板块、帖子、评论、点赞、通知、用户资料、置顶推荐;前端 Next.js 16:发帖/编辑/删除、搜索、分页、点赞、通知中心、设置;基础设施 docker-compose 与配置模板;添加 .gitignore 与专有许可证(保留所有权利)
This commit is contained in:
82
backend/service/notification.go
Normal file
82
backend/service/notification.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NotificationService 通知服务
|
||||
type NotificationService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewNotificationService(db *gorm.DB) *NotificationService {
|
||||
return &NotificationService{db: db}
|
||||
}
|
||||
|
||||
// Create 创建通知(actorID == userID 时跳过,不通知自己)
|
||||
func (s *NotificationService) Create(userID, actorID uint, notifType string, postID, commentID uint, content string) {
|
||||
if userID == 0 || actorID == 0 || userID == actorID {
|
||||
return
|
||||
}
|
||||
// 截断内容预览
|
||||
if len(content) > 200 {
|
||||
content = content[:200]
|
||||
}
|
||||
n := &model.Notification{
|
||||
UserID: userID,
|
||||
ActorID: actorID,
|
||||
Type: notifType,
|
||||
PostID: postID,
|
||||
CommentID: commentID,
|
||||
Content: content,
|
||||
IsRead: false,
|
||||
}
|
||||
// 通知创建失败不影响主流程,忽略错误
|
||||
_ = s.db.Create(n).Error
|
||||
}
|
||||
|
||||
// List 获取用户通知列表(分页,按时间倒序)
|
||||
func (s *NotificationService) List(userID uint, page, size int) ([]model.Notification, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 50 {
|
||||
size = 20
|
||||
}
|
||||
query := s.db.Model(&model.Notification{}).Where("user_id = ?", userID)
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var list []model.Notification
|
||||
offset := (page - 1) * size
|
||||
if err := query.Order("created_at DESC").Offset(offset).Limit(size).
|
||||
Preload("Actor").Preload("Post").Find(&list).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return list, total, nil
|
||||
}
|
||||
|
||||
// UnreadCount 获取未读通知数
|
||||
func (s *NotificationService) UnreadCount(userID uint) (int64, error) {
|
||||
var total int64
|
||||
err := s.db.Model(&model.Notification{}).Where("user_id = ? AND is_read = ?", userID, false).Count(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
// MarkRead 标记单条通知为已读(校验归属)
|
||||
func (s *NotificationService) MarkRead(id, userID uint) error {
|
||||
result := s.db.Model(&model.Notification{}).
|
||||
Where("id = ? AND user_id = ?", id, userID).
|
||||
Update("is_read", true)
|
||||
return result.Error
|
||||
}
|
||||
|
||||
// MarkAllRead 标记用户所有通知为已读
|
||||
func (s *NotificationService) MarkAllRead(userID uint) error {
|
||||
result := s.db.Model(&model.Notification{}).
|
||||
Where("user_id = ? AND is_read = ?", userID, false).
|
||||
Update("is_read", true)
|
||||
return result.Error
|
||||
}
|
||||
Reference in New Issue
Block a user