66 lines
1.8 KiB
Go
66 lines
1.8 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gochat/gochat/internal/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// BannerRepo provides data access for Banner.
|
|
type BannerRepo struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewBannerRepo creates a new BannerRepo.
|
|
func NewBannerRepo(db *gorm.DB) *BannerRepo {
|
|
return &BannerRepo{db: db}
|
|
}
|
|
|
|
// Create inserts a new Banner record.
|
|
func (r *BannerRepo) Create(ctx context.Context, banner *model.Banner) error {
|
|
return r.db.WithContext(ctx).Create(banner).Error
|
|
}
|
|
|
|
// FindByID retrieves a Banner by its primary key.
|
|
func (r *BannerRepo) FindByID(ctx context.Context, id uint) (*model.Banner, error) {
|
|
var banner model.Banner
|
|
err := r.db.WithContext(ctx).First(&banner, id).Error
|
|
return &banner, err
|
|
}
|
|
|
|
// List returns all banners, ordered by created_at descending.
|
|
func (r *BannerRepo) List(ctx context.Context, offset, limit int) ([]model.Banner, int64, error) {
|
|
var banners []model.Banner
|
|
var total int64
|
|
|
|
if err := r.db.WithContext(ctx).Model(&model.Banner{}).Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
err := r.db.WithContext(ctx).
|
|
Order("created_at DESC").
|
|
Offset(offset).Limit(limit).
|
|
Find(&banners).Error
|
|
return banners, total, err
|
|
}
|
|
|
|
// Update patches a Banner record by ID.
|
|
func (r *BannerRepo) Update(ctx context.Context, id uint, updates map[string]interface{}) error {
|
|
return r.db.WithContext(ctx).Model(&model.Banner{}).Where("id = ?", id).Updates(updates).Error
|
|
}
|
|
|
|
// Delete soft-deletes a Banner by ID.
|
|
func (r *BannerRepo) Delete(ctx context.Context, id uint) error {
|
|
return r.db.WithContext(ctx).Delete(&model.Banner{}, id).Error
|
|
}
|
|
|
|
// FindActive returns all active banners.
|
|
func (r *BannerRepo) FindActive(ctx context.Context) ([]model.Banner, error) {
|
|
var banners []model.Banner
|
|
err := r.db.WithContext(ctx).
|
|
Where("active = ?", true).
|
|
Order("created_at DESC").
|
|
Find(&banners).Error
|
|
return banners, err
|
|
} |