feat: implement Iteration 1 — AI recipe recommendations
Backend:
- Add Groq LLM client (llama-3.3-70b) for recipe generation with JSON
retry strategy (retries only on parse errors, not API errors)
- Add Pexels client for parallel photo search per recipe
- Add saved_recipes table (migration 004) with JSONB fields
- Add GET /recommendations endpoint (profile-aware prompt building)
- Add POST/GET/GET{id}/DELETE /saved-recipes CRUD endpoints
- Wire gemini, pexels, recommendation, savedrecipe packages in main.go
Flutter:
- Add Recipe, SavedRecipe models with json_serializable
- Add RecipeService (getRecommendations, getSavedRecipes, save, delete)
- Add RecommendationsNotifier and SavedRecipesNotifier (Riverpod)
- Add RecommendationsScreen with skeleton loading and refresh FAB
- Add RecipeDetailScreen (SliverAppBar, nutrition tooltip, steps with timer)
- Add SavedRecipesScreen with Dismissible swipe-to-delete and empty state
- Update RecipesScreen to TabBar (Recommendations / Saved)
- Add /recipe-detail route outside ShellRoute (no bottom nav)
- Extend ApiClient with getList() and deleteVoid()
Project:
- Add CLAUDE.md with English-only rule for comments and commit messages
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
135
backend/internal/savedrecipe/handler.go
Normal file
135
backend/internal/savedrecipe/handler.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package savedrecipe
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/food-ai/backend/internal/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
const maxBodySize = 1 << 20 // 1 MB
|
||||
|
||||
// Handler handles HTTP requests for saved recipes.
|
||||
type Handler struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
// NewHandler creates a new Handler.
|
||||
func NewHandler(repo *Repository) *Handler {
|
||||
return &Handler{repo: repo}
|
||||
}
|
||||
|
||||
// Save handles POST /saved-recipes.
|
||||
func (h *Handler) Save(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromCtx(r.Context())
|
||||
if userID == "" {
|
||||
writeErrorJSON(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBodySize)
|
||||
var req SaveRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErrorJSON(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if req.Title == "" {
|
||||
writeErrorJSON(w, http.StatusBadRequest, "title is required")
|
||||
return
|
||||
}
|
||||
|
||||
rec, err := h.repo.Save(r.Context(), userID, req)
|
||||
if err != nil {
|
||||
slog.Error("save recipe", "err", err)
|
||||
writeErrorJSON(w, http.StatusInternalServerError, "failed to save recipe")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, rec)
|
||||
}
|
||||
|
||||
// List handles GET /saved-recipes.
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromCtx(r.Context())
|
||||
if userID == "" {
|
||||
writeErrorJSON(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
recipes, err := h.repo.List(r.Context(), userID)
|
||||
if err != nil {
|
||||
slog.Error("list saved recipes", "err", err)
|
||||
writeErrorJSON(w, http.StatusInternalServerError, "failed to list saved recipes")
|
||||
return
|
||||
}
|
||||
|
||||
if recipes == nil {
|
||||
recipes = []*SavedRecipe{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, recipes)
|
||||
}
|
||||
|
||||
// GetByID handles GET /saved-recipes/{id}.
|
||||
func (h *Handler) GetByID(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromCtx(r.Context())
|
||||
if userID == "" {
|
||||
writeErrorJSON(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
id := chi.URLParam(r, "id")
|
||||
rec, err := h.repo.GetByID(r.Context(), userID, id)
|
||||
if err != nil {
|
||||
slog.Error("get saved recipe", "id", id, "err", err)
|
||||
writeErrorJSON(w, http.StatusInternalServerError, "failed to get saved recipe")
|
||||
return
|
||||
}
|
||||
if rec == nil {
|
||||
writeErrorJSON(w, http.StatusNotFound, "recipe not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, rec)
|
||||
}
|
||||
|
||||
// Delete handles DELETE /saved-recipes/{id}.
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromCtx(r.Context())
|
||||
if userID == "" {
|
||||
writeErrorJSON(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
id := chi.URLParam(r, "id")
|
||||
if err := h.repo.Delete(r.Context(), userID, id); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
writeErrorJSON(w, http.StatusNotFound, "recipe not found")
|
||||
return
|
||||
}
|
||||
slog.Error("delete saved recipe", "id", id, "err", err)
|
||||
writeErrorJSON(w, http.StatusInternalServerError, "failed to delete recipe")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func writeErrorJSON(w http.ResponseWriter, status int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(errorResponse{Error: msg}); err != nil {
|
||||
slog.Error("write error response", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
slog.Error("write JSON response", "err", err)
|
||||
}
|
||||
}
|
||||
43
backend/internal/savedrecipe/model.go
Normal file
43
backend/internal/savedrecipe/model.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package savedrecipe
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SavedRecipe is a recipe saved by a specific user.
|
||||
type SavedRecipe struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"-"`
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Cuisine *string `json:"cuisine"`
|
||||
Difficulty *string `json:"difficulty"`
|
||||
PrepTimeMin *int `json:"prep_time_min"`
|
||||
CookTimeMin *int `json:"cook_time_min"`
|
||||
Servings *int `json:"servings"`
|
||||
ImageURL *string `json:"image_url"`
|
||||
Ingredients json.RawMessage `json:"ingredients"`
|
||||
Steps json.RawMessage `json:"steps"`
|
||||
Tags json.RawMessage `json:"tags"`
|
||||
Nutrition json.RawMessage `json:"nutrition_per_serving"`
|
||||
Source string `json:"source"`
|
||||
SavedAt time.Time `json:"saved_at"`
|
||||
}
|
||||
|
||||
// SaveRequest is the body for POST /saved-recipes.
|
||||
type SaveRequest struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Cuisine string `json:"cuisine"`
|
||||
Difficulty string `json:"difficulty"`
|
||||
PrepTimeMin int `json:"prep_time_min"`
|
||||
CookTimeMin int `json:"cook_time_min"`
|
||||
Servings int `json:"servings"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Ingredients json.RawMessage `json:"ingredients"`
|
||||
Steps json.RawMessage `json:"steps"`
|
||||
Tags json.RawMessage `json:"tags"`
|
||||
Nutrition json.RawMessage `json:"nutrition_per_serving"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
173
backend/internal/savedrecipe/repository.go
Normal file
173
backend/internal/savedrecipe/repository.go
Normal file
@@ -0,0 +1,173 @@
|
||||
package savedrecipe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// ErrNotFound is returned when a saved recipe does not exist for the given user.
|
||||
var ErrNotFound = errors.New("saved recipe not found")
|
||||
|
||||
// Repository handles persistence for saved recipes.
|
||||
type Repository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewRepository creates a new Repository.
|
||||
func NewRepository(pool *pgxpool.Pool) *Repository {
|
||||
return &Repository{pool: pool}
|
||||
}
|
||||
|
||||
// Save persists a recipe for userID and returns the stored record.
|
||||
func (r *Repository) Save(ctx context.Context, userID string, req SaveRequest) (*SavedRecipe, error) {
|
||||
const query = `
|
||||
INSERT INTO saved_recipes (
|
||||
user_id, title, description, cuisine, difficulty,
|
||||
prep_time_min, cook_time_min, servings, image_url,
|
||||
ingredients, steps, tags, nutrition, source
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
RETURNING id, user_id, title, description, cuisine, difficulty,
|
||||
prep_time_min, cook_time_min, servings, image_url,
|
||||
ingredients, steps, tags, nutrition, source, saved_at`
|
||||
|
||||
description := nullableStr(req.Description)
|
||||
cuisine := nullableStr(req.Cuisine)
|
||||
difficulty := nullableStr(req.Difficulty)
|
||||
imageURL := nullableStr(req.ImageURL)
|
||||
prepTime := nullableInt(req.PrepTimeMin)
|
||||
cookTime := nullableInt(req.CookTimeMin)
|
||||
servings := nullableInt(req.Servings)
|
||||
|
||||
source := req.Source
|
||||
if source == "" {
|
||||
source = "ai"
|
||||
}
|
||||
|
||||
ingredients := defaultJSONArray(req.Ingredients)
|
||||
steps := defaultJSONArray(req.Steps)
|
||||
tags := defaultJSONArray(req.Tags)
|
||||
|
||||
row := r.pool.QueryRow(ctx, query,
|
||||
userID, req.Title, description, cuisine, difficulty,
|
||||
prepTime, cookTime, servings, imageURL,
|
||||
ingredients, steps, tags, req.Nutrition, source,
|
||||
)
|
||||
return scanRow(row)
|
||||
}
|
||||
|
||||
// List returns all saved recipes for userID ordered by saved_at DESC.
|
||||
func (r *Repository) List(ctx context.Context, userID string) ([]*SavedRecipe, error) {
|
||||
const query = `
|
||||
SELECT id, user_id, title, description, cuisine, difficulty,
|
||||
prep_time_min, cook_time_min, servings, image_url,
|
||||
ingredients, steps, tags, nutrition, source, saved_at
|
||||
FROM saved_recipes
|
||||
WHERE user_id = $1
|
||||
ORDER BY saved_at DESC`
|
||||
|
||||
rows, err := r.pool.Query(ctx, query, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list saved recipes: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*SavedRecipe
|
||||
for rows.Next() {
|
||||
rec, err := scanRows(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan saved recipe: %w", err)
|
||||
}
|
||||
result = append(result, rec)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// GetByID returns the saved recipe with id for userID, or nil if not found.
|
||||
func (r *Repository) GetByID(ctx context.Context, userID, id string) (*SavedRecipe, error) {
|
||||
const query = `
|
||||
SELECT id, user_id, title, description, cuisine, difficulty,
|
||||
prep_time_min, cook_time_min, servings, image_url,
|
||||
ingredients, steps, tags, nutrition, source, saved_at
|
||||
FROM saved_recipes
|
||||
WHERE id = $1 AND user_id = $2`
|
||||
|
||||
rec, err := scanRow(r.pool.QueryRow(ctx, query, id, userID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
|
||||
// Delete removes the saved recipe with id for userID.
|
||||
// Returns ErrNotFound if the record does not exist.
|
||||
func (r *Repository) Delete(ctx context.Context, userID, id string) error {
|
||||
tag, err := r.pool.Exec(ctx,
|
||||
`DELETE FROM saved_recipes WHERE id = $1 AND user_id = $2`,
|
||||
id, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete saved recipe: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanRow(s scannable) (*SavedRecipe, error) {
|
||||
var rec SavedRecipe
|
||||
var ingredients, steps, tags, nutrition []byte
|
||||
err := s.Scan(
|
||||
&rec.ID, &rec.UserID, &rec.Title, &rec.Description, &rec.Cuisine, &rec.Difficulty,
|
||||
&rec.PrepTimeMin, &rec.CookTimeMin, &rec.Servings, &rec.ImageURL,
|
||||
&ingredients, &steps, &tags, &nutrition,
|
||||
&rec.Source, &rec.SavedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rec.Ingredients = json.RawMessage(ingredients)
|
||||
rec.Steps = json.RawMessage(steps)
|
||||
rec.Tags = json.RawMessage(tags)
|
||||
if len(nutrition) > 0 {
|
||||
rec.Nutrition = json.RawMessage(nutrition)
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
// scanRows wraps pgx.Rows to satisfy the scannable interface.
|
||||
func scanRows(rows pgx.Rows) (*SavedRecipe, error) {
|
||||
return scanRow(rows)
|
||||
}
|
||||
|
||||
func nullableStr(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func nullableInt(n int) *int {
|
||||
if n <= 0 {
|
||||
return nil
|
||||
}
|
||||
return &n
|
||||
}
|
||||
|
||||
func defaultJSONArray(raw json.RawMessage) json.RawMessage {
|
||||
if len(raw) == 0 {
|
||||
return json.RawMessage(`[]`)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
Reference in New Issue
Block a user