Files
hfb_sys/backend/internal/modules/notification/repository.go
T
yml2213 b377f8350b 为 9 个模块添加 Context 超时控制
完成模块:
- auth: 3 个 Repository 方法 + Service + Handler + Middleware
- wallet: 已有 context 支持,修复依赖调用
- payment: 已有 context 支持,修复 wallet 调用
- adminaudit: 1 个方法
- notification: 2 个方法
- realname: 2 个方法
- systemconfig: 4 个方法
- adminauth: 7 个方法
- adminuser: 6 个方法

所有数据库调用已改为 r.db.WithContext(ctx),完整传递 context 链路。

待完成模块: order, listing, chat 等 12 个模块(约 157 个方法)
2026-06-10 09:12:27 +08:00

89 lines
2.0 KiB
Go

package notification
import (
"context"
"time"
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
)
type Repository struct {
db *gorm.DB
}
type Entry struct {
UserID uint64
Type string
Title string
Content string
BizType string
BizID *uint64
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
var total int64
if err := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
return nil, err
}
offset := (page - 1) * pageSize
var rows []model.Notification
if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Order("id DESC").Offset(offset).Limit(pageSize).Find(&rows).Error; err != nil {
return nil, err
}
items := make([]NotificationDTO, 0, len(rows))
for _, row := range rows {
items = append(items, toDTO(row))
}
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
}
func (r *Repository) MarkRead(ctx context.Context, userID uint64, id uint64) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&model.Notification{}).
Where("id = ? AND user_id = ?", id, userID).
Update("read_at", now).Error
}
func Append(tx *gorm.DB, entries ...Entry) error {
for _, entry := range entries {
if entry.UserID == 0 || entry.Title == "" {
continue
}
row := model.Notification{
UserID: entry.UserID,
Type: entry.Type,
Title: entry.Title,
Content: entry.Content,
BizType: entry.BizType,
BizID: entry.BizID,
}
if row.Type == "" {
row.Type = "system"
}
if err := tx.Create(&row).Error; err != nil {
return err
}
}
return nil
}
func toDTO(row model.Notification) NotificationDTO {
return NotificationDTO{
ID: row.ID,
UserID: row.UserID,
Type: row.Type,
Title: row.Title,
Content: row.Content,
BizType: row.BizType,
BizID: row.BizID,
ReadAt: row.ReadAt,
CreatedAt: row.CreatedAt,
}
}