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>
This commit is contained in:
dbastrikin
2026-03-15 18:45:21 +02:00
parent 61feb91bba
commit 0ce111fa08
14 changed files with 552 additions and 423 deletions

View File

@@ -2,9 +2,11 @@ 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 {
@@ -12,17 +14,47 @@ type cuisineItem struct {
Name string `json:"name"`
}
// List handles GET /cuisines — returns cuisines with names in the requested language.
func List(w http.ResponseWriter, r *http.Request) {
lang := locale.FromContext(r.Context())
items := make([]cuisineItem, 0, len(Records))
for _, c := range Records {
name, ok := c.Translations[lang]
if !ok {
name = c.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
}
items = append(items, cuisineItem{Slug: c.Slug, Name: name})
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})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).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})
}

View File

@@ -1,80 +0,0 @@
package cuisine
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
)
// Record is a cuisine loaded from DB with all its translations.
type Record struct {
Slug string
Name string // English canonical name
SortOrder int
// Translations maps lang code to localized name.
Translations map[string]string
}
// Records is the ordered list of cuisines, populated by LoadFromDB at startup.
var Records []Record
// LoadFromDB queries cuisines + cuisine_translations and populates Records.
func LoadFromDB(ctx context.Context, pool *pgxpool.Pool) error {
rows, err := pool.Query(ctx, `
SELECT c.slug, c.name, c.sort_order, ct.lang, ct.name
FROM cuisines c
LEFT JOIN cuisine_translations ct ON ct.cuisine_slug = c.slug
ORDER BY c.sort_order, ct.lang`)
if err != nil {
return fmt.Errorf("load cuisines from db: %w", err)
}
defer rows.Close()
bySlug := map[string]*Record{}
var order []string
for rows.Next() {
var slug, engName string
var sortOrder int
var lang, name *string
if err := rows.Scan(&slug, &engName, &sortOrder, &lang, &name); err != nil {
return err
}
if _, ok := bySlug[slug]; !ok {
bySlug[slug] = &Record{
Slug: slug,
Name: engName,
SortOrder: sortOrder,
Translations: map[string]string{},
}
order = append(order, slug)
}
if lang != nil && name != nil {
bySlug[slug].Translations[*lang] = *name
}
}
if err := rows.Err(); err != nil {
return err
}
result := make([]Record, 0, len(order))
for _, slug := range order {
result = append(result, *bySlug[slug])
}
Records = result
return nil
}
// NameFor returns the localized name for a cuisine slug.
// Falls back to the English canonical name.
func NameFor(slug, lang string) string {
for _, c := range Records {
if c.Slug == slug {
if name, ok := c.Translations[lang]; ok {
return name
}
return c.Name
}
}
return slug
}

View File

@@ -13,8 +13,8 @@ import (
"github.com/food-ai/backend/internal/middleware"
)
// ingredientRepo is the subset of ingredient.Repository used by this handler.
type ingredientRepo interface {
// IngredientRepository is the subset of ingredient.Repository used by this handler.
type IngredientRepository interface {
FuzzyMatch(ctx context.Context, name string) (*ingredient.IngredientMapping, error)
Upsert(ctx context.Context, m *ingredient.IngredientMapping) (*ingredient.IngredientMapping, error)
UpsertTranslation(ctx context.Context, id, lang, name string) error
@@ -24,11 +24,11 @@ type ingredientRepo interface {
// Handler handles POST /ai/* recognition endpoints.
type Handler struct {
gemini *gemini.Client
ingredientRepo ingredientRepo
ingredientRepo IngredientRepository
}
// NewHandler creates a new Handler.
func NewHandler(geminiClient *gemini.Client, repo ingredientRepo) *Handler {
func NewHandler(geminiClient *gemini.Client, repo IngredientRepository) *Handler {
return &Handler{gemini: geminiClient, ingredientRepo: repo}
}

View File

@@ -5,7 +5,6 @@ import (
"net/http"
"github.com/food-ai/backend/internal/auth"
"github.com/food-ai/backend/internal/cuisine"
"github.com/food-ai/backend/internal/diary"
"github.com/food-ai/backend/internal/dish"
"github.com/food-ai/backend/internal/home"
@@ -14,8 +13,6 @@ import (
"github.com/food-ai/backend/internal/menu"
"github.com/food-ai/backend/internal/middleware"
"github.com/food-ai/backend/internal/recipe"
"github.com/food-ai/backend/internal/tag"
"github.com/food-ai/backend/internal/units"
"github.com/food-ai/backend/internal/product"
"github.com/food-ai/backend/internal/recognition"
"github.com/food-ai/backend/internal/recommendation"
@@ -41,6 +38,9 @@ func NewRouter(
recipeHandler *recipe.Handler,
authMiddleware func(http.Handler) http.Handler,
allowedOrigins []string,
unitsListHandler http.HandlerFunc,
cuisineListHandler http.HandlerFunc,
tagListHandler http.HandlerFunc,
) *chi.Mux {
r := chi.NewRouter()
@@ -54,9 +54,9 @@ func NewRouter(
// Public
r.Get("/health", healthCheck(pool))
r.Get("/languages", language.List)
r.Get("/units", units.List)
r.Get("/cuisines", cuisine.List)
r.Get("/tags", tag.List)
r.Get("/units", unitsListHandler)
r.Get("/cuisines", cuisineListHandler)
r.Get("/tags", tagListHandler)
r.Route("/auth", func(r chi.Router) {
r.Post("/login", authHandler.Login)
r.Post("/refresh", authHandler.Refresh)

View File

@@ -2,9 +2,11 @@ package tag
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/locale"
"github.com/jackc/pgx/v5/pgxpool"
)
type tagItem struct {
@@ -12,17 +14,47 @@ type tagItem struct {
Name string `json:"name"`
}
// List handles GET /tags — returns tags with names in the requested language.
func List(w http.ResponseWriter, r *http.Request) {
lang := locale.FromContext(r.Context())
items := make([]tagItem, 0, len(Records))
for _, t := range Records {
name, ok := t.Translations[lang]
if !ok {
name = t.Name
// NewListHandler returns an http.HandlerFunc for GET /tags.
// 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 t.slug, COALESCE(tt.name, t.name) AS name
FROM tags t
LEFT JOIN tag_translations tt ON tt.tag_slug = t.slug AND tt.lang = $1
ORDER BY t.sort_order`, lang)
if queryError != nil {
slog.Error("list tags", "err", queryError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load tags")
return
}
items = append(items, tagItem{Slug: t.Slug, Name: name})
defer rows.Close()
items := make([]tagItem, 0)
for rows.Next() {
var item tagItem
if scanError := rows.Scan(&item.Slug, &item.Name); scanError != nil {
slog.Error("scan tag row", "err", scanError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load tags")
return
}
items = append(items, item)
}
if rowsError := rows.Err(); rowsError != nil {
slog.Error("iterate tag rows", "err", rowsError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load tags")
return
}
responseWriter.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(responseWriter).Encode(map[string]any{"tags": items})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"tags": 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})
}

View File

@@ -1,79 +0,0 @@
package tag
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
)
// Record is a tag loaded from DB with all its translations.
type Record struct {
Slug string
Name string // English canonical name
SortOrder int
Translations map[string]string // lang → localized name
}
// Records is the ordered list of tags, populated by LoadFromDB at startup.
var Records []Record
// LoadFromDB queries tags + tag_translations and populates Records.
func LoadFromDB(ctx context.Context, pool *pgxpool.Pool) error {
rows, err := pool.Query(ctx, `
SELECT t.slug, t.name, t.sort_order, tt.lang, tt.name
FROM tags t
LEFT JOIN tag_translations tt ON tt.tag_slug = t.slug
ORDER BY t.sort_order, tt.lang`)
if err != nil {
return fmt.Errorf("load tags from db: %w", err)
}
defer rows.Close()
bySlug := map[string]*Record{}
var order []string
for rows.Next() {
var slug, engName string
var sortOrder int
var lang, name *string
if err := rows.Scan(&slug, &engName, &sortOrder, &lang, &name); err != nil {
return err
}
if _, ok := bySlug[slug]; !ok {
bySlug[slug] = &Record{
Slug: slug,
Name: engName,
SortOrder: sortOrder,
Translations: map[string]string{},
}
order = append(order, slug)
}
if lang != nil && name != nil {
bySlug[slug].Translations[*lang] = *name
}
}
if err := rows.Err(); err != nil {
return err
}
result := make([]Record, 0, len(order))
for _, slug := range order {
result = append(result, *bySlug[slug])
}
Records = result
return nil
}
// NameFor returns the localized name for a tag slug.
// Falls back to the English canonical name.
func NameFor(slug, lang string) string {
for _, t := range Records {
if t.Slug == slug {
if name, ok := t.Translations[lang]; ok {
return name
}
return t.Name
}
}
return slug
}

View File

@@ -2,9 +2,11 @@ package units
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/locale"
"github.com/jackc/pgx/v5/pgxpool"
)
type unitItem struct {
@@ -12,17 +14,47 @@ type unitItem struct {
Name string `json:"name"`
}
// List handles GET /units — returns units with names in the requested language.
func List(w http.ResponseWriter, r *http.Request) {
lang := locale.FromContext(r.Context())
items := make([]unitItem, 0, len(Records))
for _, u := range Records {
name, ok := u.Translations[lang]
if !ok {
name = u.Code // fallback to English code
// NewListHandler returns an http.HandlerFunc for GET /units.
// 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 u.code, COALESCE(ut.name, u.code) AS name
FROM units u
LEFT JOIN unit_translations ut ON ut.unit_code = u.code AND ut.lang = $1
ORDER BY u.sort_order`, lang)
if queryError != nil {
slog.Error("list units", "err", queryError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load units")
return
}
items = append(items, unitItem{Code: u.Code, Name: name})
defer rows.Close()
items := make([]unitItem, 0)
for rows.Next() {
var item unitItem
if scanError := rows.Scan(&item.Code, &item.Name); scanError != nil {
slog.Error("scan unit row", "err", scanError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load units")
return
}
items = append(items, item)
}
if rowsError := rows.Err(); rowsError != nil {
slog.Error("iterate unit rows", "err", rowsError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to load units")
return
}
responseWriter.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(responseWriter).Encode(map[string]any{"units": items})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"units": 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})
}

View File

@@ -1,73 +0,0 @@
package units
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
)
// Record is a unit loaded from DB with all its translations.
type Record struct {
Code string
SortOrder int
Translations map[string]string // lang → localized name
}
// Records is the ordered list of active units, populated by LoadFromDB at startup.
var Records []Record
// LoadFromDB queries units + unit_translations and populates Records.
func LoadFromDB(ctx context.Context, pool *pgxpool.Pool) error {
rows, err := pool.Query(ctx, `
SELECT u.code, u.sort_order, ut.lang, ut.name
FROM units u
LEFT JOIN unit_translations ut ON ut.unit_code = u.code
ORDER BY u.sort_order, ut.lang`)
if err != nil {
return fmt.Errorf("load units from db: %w", err)
}
defer rows.Close()
byCode := map[string]*Record{}
var order []string
for rows.Next() {
var code string
var sortOrder int
var lang, name *string
if err := rows.Scan(&code, &sortOrder, &lang, &name); err != nil {
return err
}
if _, ok := byCode[code]; !ok {
byCode[code] = &Record{Code: code, SortOrder: sortOrder, Translations: map[string]string{}}
order = append(order, code)
}
if lang != nil && name != nil {
byCode[code].Translations[*lang] = *name
}
}
if err := rows.Err(); err != nil {
return err
}
result := make([]Record, 0, len(order))
for _, code := range order {
result = append(result, *byCode[code])
}
Records = result
return nil
}
// NameFor returns the localized name for a unit code.
// Falls back to the code itself when no translation exists.
func NameFor(code, lang string) string {
for _, u := range Records {
if u.Code == code {
if name, ok := u.Translations[lang]; ok {
return name
}
return u.Code
}
}
return code
}