105 lines
2.6 KiB
Go
105 lines
2.6 KiB
Go
package repository
|
||
|
||
import (
|
||
"errors"
|
||
|
||
appErrors "github.com/topfans/backend/pkg/errors"
|
||
"github.com/topfans/backend/pkg/database"
|
||
"github.com/topfans/backend/pkg/models"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
// StarRepository 明星Repository接口
|
||
type StarRepository interface {
|
||
// GetByID 根据ID查询
|
||
GetByID(starID int64) (*models.Star, error)
|
||
|
||
// GetByIdentityID 根据identity_id查询
|
||
GetByIdentityID(identityID string) (*models.Star, error)
|
||
|
||
// GetAllActive 获取所有可用明星列表
|
||
GetAllActive() ([]*models.Star, error)
|
||
|
||
// Search 搜索明星(按名称)
|
||
Search(keyword string) ([]*models.Star, error)
|
||
}
|
||
|
||
// starRepository 明星Repository实现
|
||
type starRepository struct {
|
||
db *gorm.DB
|
||
}
|
||
|
||
// NewStarRepository 创建明星Repository实例
|
||
func NewStarRepository() StarRepository {
|
||
return &starRepository{
|
||
db: database.GetDB(),
|
||
}
|
||
}
|
||
|
||
// GetByID 根据ID查询
|
||
func (r *starRepository) GetByID(starID int64) (*models.Star, error) {
|
||
if starID <= 0 {
|
||
return nil, errors.New("star_id must be greater than 0")
|
||
}
|
||
|
||
var star models.Star
|
||
if err := r.db.Where("star_id = ? AND is_active = ?", starID, true).
|
||
First(&star).Error; err != nil {
|
||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||
return nil, appErrors.ErrStarNotFound
|
||
}
|
||
return nil, err
|
||
}
|
||
|
||
return &star, nil
|
||
}
|
||
|
||
// GetByIdentityID 根据identity_id查询
|
||
func (r *starRepository) GetByIdentityID(identityID string) (*models.Star, error) {
|
||
if identityID == "" {
|
||
return nil, errors.New("identity_id cannot be empty")
|
||
}
|
||
|
||
var star models.Star
|
||
if err := r.db.Where("identity_id = ? AND is_active = ?", identityID, true).
|
||
First(&star).Error; err != nil {
|
||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||
return nil, appErrors.ErrStarNotFound
|
||
}
|
||
return nil, err
|
||
}
|
||
|
||
return &star, nil
|
||
}
|
||
|
||
// GetAllActive 获取所有可用明星列表
|
||
func (r *starRepository) GetAllActive() ([]*models.Star, error) {
|
||
var stars []*models.Star
|
||
if err := r.db.Where("is_active = ?", true).
|
||
Order("created_at ASC").
|
||
Find(&stars).Error; err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
return stars, nil
|
||
}
|
||
|
||
// Search 搜索明星(按名称、tag、identity_id)
|
||
func (r *starRepository) Search(keyword string) ([]*models.Star, error) {
|
||
if keyword == "" {
|
||
return r.GetAllActive()
|
||
}
|
||
|
||
var stars []*models.Star
|
||
searchPattern := "%" + keyword + "%"
|
||
// 搜索 name, name_en, tag, identity_id
|
||
if err := r.db.Where("is_active = ? AND (name LIKE ? OR name_en LIKE ? OR tag LIKE ? OR identity_id LIKE ?)",
|
||
true, searchPattern, searchPattern, searchPattern, searchPattern).
|
||
Order("created_at ASC").
|
||
Find(&stars).Error; err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
return stars, nil
|
||
}
|