fix: improve error handling in categories service

- Slug collision checks now properly propagate real DB errors instead of
  silently ignoring them
- GetCategory now verifies site ownership, matching the pattern used by
  UpdateCategory and DeleteCategory

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Leon Mika 2026-03-18 22:11:33 +11:00
parent 6c69131b03
commit 9efa40879f

View file

@ -61,7 +61,19 @@ func (s *Service) ListCategoriesWithCounts(ctx context.Context) ([]models.Catego
}
func (s *Service) GetCategory(ctx context.Context, id int64) (*models.Category, error) {
return s.db.SelectCategory(ctx, id)
site, ok := models.GetSite(ctx)
if !ok {
return nil, models.SiteRequiredError
}
cat, err := s.db.SelectCategory(ctx, id)
if err != nil {
return nil, err
}
if cat.SiteID != site.ID {
return nil, models.NotFoundError
}
return cat, nil
}
func (s *Service) CreateCategory(ctx context.Context, params CreateCategoryParams) (*models.Category, error) {
@ -79,6 +91,8 @@ func (s *Service) CreateCategory(ctx context.Context, params CreateCategoryParam
// Check for slug collision
if _, err := s.db.SelectCategoryBySlugAndSite(ctx, site.ID, slug); err == nil {
return nil, models.SlugConflictError
} else if !db.ErrorIsNoRows(err) {
return nil, err
}
cat := &models.Category{
@ -124,6 +138,8 @@ func (s *Service) UpdateCategory(ctx context.Context, id int64, params CreateCat
// Check slug collision (exclude self)
if existing, err := s.db.SelectCategoryBySlugAndSite(ctx, site.ID, slug); err == nil && existing.ID != cat.ID {
return nil, models.SlugConflictError
} else if err != nil && !db.ErrorIsNoRows(err) {
return nil, err
}
cat.Name = params.Name