This commit is contained in:
toom1996
2026-09-03 00:32:52 +08:00
parent 1fd9c48f58
commit ffe84efc4c
9 changed files with 143 additions and 39 deletions

View File

@ -10,11 +10,13 @@ import (
)
// FavoriteRepository 收藏数据访问接口。
//
// kind 用于区分收藏粒度(gallery=整篇图集 / image=单张图片);传空表示不限粒度。
type FavoriteRepository interface {
// ListPaged 分页取某用户收藏,按收藏时间倒序。
ListPaged(ctx context.Context, userID uint32, page, perPage int) ([]model.Favorite, error)
ListPaged(ctx context.Context, userID uint32, page, perPage int, kind string) ([]model.Favorite, error)
// CountByUser 取某用户收藏总数(分页用)。
CountByUser(ctx context.Context, userID uint32) (int64, error)
CountByUser(ctx context.Context, userID uint32, kind string) (int64, error)
// Add 新增收藏;同用户同 target 已存在时幂等忽略(ON DUPLICATE KEY DO NOTHING)。
Add(ctx context.Context, f *model.Favorite) error
// Remove 删除某用户对某个 target 的收藏。
@ -32,14 +34,17 @@ func NewFavoriteRepository(db *gorm.DB) FavoriteRepository {
return &favoriteRepository{db: db}
}
func (r *favoriteRepository) ListPaged(ctx context.Context, userID uint32, page, perPage int) ([]model.Favorite, error) {
func (r *favoriteRepository) ListPaged(ctx context.Context, userID uint32, page, perPage int, kind string) ([]model.Favorite, error) {
var rows []model.Favorite
offset := (page - 1) * perPage
if offset < 0 {
offset = 0
}
err := r.db.WithContext(ctx).
Where("user_id = ?", userID).
q := r.db.WithContext(ctx).Where("user_id = ?", userID)
if kind != "" {
q = q.Where("kind = ?", kind)
}
err := q.
Order("created_at DESC").
Offset(offset).
Limit(perPage).
@ -47,12 +52,15 @@ func (r *favoriteRepository) ListPaged(ctx context.Context, userID uint32, page,
return rows, err
}
func (r *favoriteRepository) CountByUser(ctx context.Context, userID uint32) (int64, error) {
func (r *favoriteRepository) CountByUser(ctx context.Context, userID uint32, kind string) (int64, error) {
var n int64
err := r.db.WithContext(ctx).
q := r.db.WithContext(ctx).
Model(&model.Favorite{}).
Where("user_id = ?", userID).
Count(&n).Error
Where("user_id = ?", userID)
if kind != "" {
q = q.Where("kind = ?", kind)
}
err := q.Count(&n).Error
return n, err
}