Files
food-ai/backend/internal/cuisine/handler.go
dbastrikin 0ce111fa08 refactor: migrate DI to Wire, replace startup registries with on-demand DB queries
- Add google/wire; generate wire_gen.go from wire.go injector
- Move all constructor wiring out of main.go into providers.go / wire.go
- Export recognition.IngredientRepository (was unexported, blocked Wire binding)
- Delete units/cuisine/tag registry.go files (global state + unused NameFor helpers)
- Replace List handlers with NewListHandler(pool) using COALESCE SQL queries
- Remove units/cuisine/tag LoadFromDB from server startup; locale.LoadFromDB kept
  (locale.Supported is used by language middleware on every request)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 18:45:21 +02:00

61 lines
1.9 KiB
Go

package cuisine
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/locale"
"github.com/jackc/pgx/v5/pgxpool"
)
type cuisineItem struct {
Slug string `json:"slug"`
Name string `json:"name"`
}
// NewListHandler returns an http.HandlerFunc for GET /cuisines.
// It queries the database directly, resolving translations via COALESCE.
func NewListHandler(pool *pgxpool.Pool) http.HandlerFunc {
return func(responseWriter http.ResponseWriter, request *http.Request) {
lang := locale.FromContext(request.Context())
rows, queryError := pool.Query(request.Context(), `
SELECT c.slug, COALESCE(ct.name, c.name) AS name
FROM cuisines c
LEFT JOIN cuisine_translations ct ON ct.cuisine_slug = c.slug AND ct.lang = $1
ORDER BY c.sort_order`, lang)
if queryError != nil {
slog.Error("list cuisines", "err", queryError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load cuisines")
return
}
defer rows.Close()
items := make([]cuisineItem, 0)
for rows.Next() {
var item cuisineItem
if scanError := rows.Scan(&item.Slug, &item.Name); scanError != nil {
slog.Error("scan cuisine row", "err", scanError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load cuisines")
return
}
items = append(items, item)
}
if rowsError := rows.Err(); rowsError != nil {
slog.Error("iterate cuisine rows", "err", rowsError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load cuisines")
return
}
responseWriter.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(responseWriter).Encode(map[string]any{"cuisines": items})
}
}
func writeErrorJSON(responseWriter http.ResponseWriter, status int, message string) {
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(status)
_ = json.NewEncoder(responseWriter).Encode(map[string]string{"error": message})
}