recipes2/internal/http-server/handlers/recipesByCategory/recipesByCategory.go

80 lines
2.2 KiB
Go
Raw Normal View History

package recipes_by_category
import (
"context"
2024-01-29 14:32:35 +02:00
"errors"
"log/slog"
"net/http"
"recipes/internal/domain/models"
resp "recipes/internal/lib/api/response"
"recipes/internal/lib/logger/sl"
2024-01-29 14:32:35 +02:00
"recipes/internal/storage"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"github.com/go-playground/validator/v10"
)
type Request struct {
Page uint `json:"page" validate:"required,gt=0"`
2024-01-27 20:42:23 +02:00
Category string `json:"category" validate:"required"`
}
type Response struct {
resp.Response
Recipes []models.Recipe `json:"recipes"`
}
2024-01-28 10:37:18 +02:00
//go:generate go run github.com/vektra/mockery/v2@v2.40.1 --name=RecipesProvider
type RecipesProvider interface {
GetRecipesByCategory(ctx context.Context, offset, limit int, category string) ([]models.Recipe, error)
}
2024-01-29 14:32:35 +02:00
const GetRecipesLimit int = 16
func New(log *slog.Logger, recipesProvider RecipesProvider) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
const op = "http-server.handlers.recipesByCategory.New"
2024-01-27 20:42:23 +02:00
log := log.With(
slog.String("op", op),
slog.String("request_id", middleware.GetReqID(r.Context())),
)
var req Request
// decode request
err := render.DecodeJSON(r.Body, &req)
if err != nil {
log.Error("failed to decode request body", sl.Err(err))
render.JSON(w, r, resp.Error("failed to decode request"))
return
}
log.Debug("request body decoded", slog.Any("request", req))
// validate request
if err := validator.New().Struct(req); err != nil {
validateErr := err.(validator.ValidationErrors)
log.Error("invalid request", sl.Err(err))
render.JSON(w, r, resp.ValidationError(validateErr))
return
}
// get recipes from storage
2024-01-29 14:32:35 +02:00
recipes, err := recipesProvider.GetRecipesByCategory(r.Context(), GetRecipesLimit*(int(req.Page)-1), GetRecipesLimit, req.Category)
if err != nil {
2024-01-29 14:32:35 +02:00
if errors.Is(err, storage.ErrCategoryNotFound) {
log.Error("failed to get recipes by category from storage", sl.Err(err))
render.JSON(w, r, resp.Error("category not found"))
return
}
log.Error("failed to get recipes from storage", sl.Err(err))
render.JSON(w, r, resp.Error("failed to get recipes"))
return
}
// return
render.JSON(w, r, Response{
Response: resp.OK(),
Recipes: recipes,
})
}
}