Files
food-ai/backend/internal/domain/ingredient/handler.go
dbastrikin bfaca1a2c1 test: expand test coverage across diary, product, savedrecipe, ingredient, menu, recognition
- Fix locale_test: add TestMain to pre-populate Supported map so zh/es tests pass
- Export pure functions for testability: ResolveWeekStart, MapCuisineSlug (menu + savedrecipe), MergeAndDeduplicate
- Introduce repository interfaces (DiaryRepository, ProductRepository, SavedRecipeRepository, IngredientSearcher) in each handler; NewHandler now accepts interfaces — concrete *Repository still satisfies them
- Add mock files: diary/mocks, product/mocks, savedrecipe/mocks
- Add handler unit tests (no DB) for diary (8), product (8), savedrecipe (8), ingredient (5)
- Add pure-function unit tests: menu/ResolveWeekStart (6), savedrecipe/MapCuisineSlug (5), recognition/MergeAndDeduplicate (6)
- Add repository integration tests (//go:build integration): diary (4), product (6)
- Extend recipe integration tests: GetByID_Found, GetByID_WithTranslation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 22:54:09 +02:00

58 lines
1.3 KiB
Go

package ingredient
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strconv"
)
// IngredientSearcher is the data layer interface used by Handler.
type IngredientSearcher interface {
Search(ctx context.Context, query string, limit int) ([]*IngredientMapping, error)
}
// Handler handles ingredient HTTP requests.
type Handler struct {
repo IngredientSearcher
}
// NewHandler creates a new Handler.
func NewHandler(repo IngredientSearcher) *Handler {
return &Handler{repo: repo}
}
// Search handles GET /ingredients/search?q=&limit=10.
func (h *Handler) Search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
if q == "" {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte("[]"))
return
}
limit := 10
if s := r.URL.Query().Get("limit"); s != "" {
if n, err := strconv.Atoi(s); err == nil && n > 0 && n <= 50 {
limit = n
}
}
mappings, err := h.repo.Search(r.Context(), q, limit)
if err != nil {
slog.Error("search ingredients", "q", q, "err", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"search failed"}`))
return
}
if mappings == nil {
mappings = []*IngredientMapping{}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(mappings)
}