tercul-backend/internal/repositories/category_repository.go
Damir Mukimov fa336cacf3
wip
2025-09-01 00:43:59 +02:00

68 lines
2.1 KiB
Go

package repositories
import (
"context"
"errors"
"gorm.io/gorm"
"tercul/internal/models"
)
// CategoryRepository defines CRUD methods specific to Category.
type CategoryRepository interface {
BaseRepository[models.Category]
FindByName(ctx context.Context, name string) (*models.Category, error)
ListByWorkID(ctx context.Context, workID uint) ([]models.Category, error)
ListByParentID(ctx context.Context, parentID *uint) ([]models.Category, error)
}
type categoryRepository struct {
BaseRepository[models.Category]
db *gorm.DB
}
// NewCategoryRepository creates a new CategoryRepository.
func NewCategoryRepository(db *gorm.DB) CategoryRepository {
return &categoryRepository{
BaseRepository: NewBaseRepositoryImpl[models.Category](db),
db: db,
}
}
// FindByName finds a category by name
func (r *categoryRepository) FindByName(ctx context.Context, name string) (*models.Category, error) {
var category models.Category
if err := r.db.WithContext(ctx).Where("name = ?", name).First(&category).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrEntityNotFound
}
return nil, err
}
return &category, nil
}
// ListByWorkID finds categories by work ID
func (r *categoryRepository) ListByWorkID(ctx context.Context, workID uint) ([]models.Category, error) {
var categories []models.Category
if err := r.db.WithContext(ctx).Joins("JOIN work_categories ON work_categories.category_id = categories.id").
Where("work_categories.work_id = ?", workID).
Find(&categories).Error; err != nil {
return nil, err
}
return categories, nil
}
// ListByParentID finds categories by parent ID
func (r *categoryRepository) ListByParentID(ctx context.Context, parentID *uint) ([]models.Category, error) {
var categories []models.Category
if parentID == nil {
if err := r.db.WithContext(ctx).Where("parent_id IS NULL").Find(&categories).Error; err != nil {
return nil, err
}
} else {
if err := r.db.WithContext(ctx).Where("parent_id = ?", *parentID).Find(&categories).Error; err != nil {
return nil, err
}
}
return categories, nil
}