From f60736d0889c028575cdd8c475b48bd4f836019a Mon Sep 17 00:00:00 2001 From: Everest Date: Sun, 28 Jan 2024 23:09:53 -0300 Subject: [PATCH] Refactor query processing and user retrieval Introduce QueryParams struct to encapsulate request query parameters, streamlining the extraction and usage within the lending handler. Also, centralize user extraction logic by adding GetUserFromCtx function, improving code reusability and clarity. Error handling is enhanced by logging issues during query parameter parsing. Resolves user handling inconsistency and simplifies event query construction. --- pkg/lending/handler.go | 25 ++++++++++++++++++++----- pkg/user/middleware.go | 8 ++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/pkg/lending/handler.go b/pkg/lending/handler.go index 018a0c9..ec0bd14 100644 --- a/pkg/lending/handler.go +++ b/pkg/lending/handler.go @@ -1,6 +1,7 @@ package lending import ( + "log/slog" "net/http" "github.com/labstack/echo/v4" @@ -11,16 +12,30 @@ import ( "github.com/marcopollivier/techagenda/pkg/user" ) +type QueryParams struct { + Name string `query:"name"` + City string `query:"city"` + Tags []string `query:"tags"` + TypeOf []event.EventTypeOf `query:"type_of"` + Available bool `query:"available"` + Page int `query:"page"` + Limit int `query:"limit"` +} + func NewLendingHandler(server *echo.Echo, eventService event.Service, engine *ssr.Engine) { server.Static("/assets", "./ui/public/") server.GET("/v2", func(c echo.Context) (err error) { - var userPtr *user.User - events, _ := eventService.Get(c.Request().Context(), "", "", []string{}, []event.EventTypeOf{}, false, 0, 50) - if userData, ok := c.Request().Context().Value(user.MiddlewareUserKey).(user.User); ok { - userPtr = &userData + var ( + ctx = c.Request().Context() + qp QueryParams + ) + if err = c.Bind(&qp); err != nil { + slog.ErrorContext(ctx, "Error parsing query params", "error", err.Error()) } + events, _ := eventService.Get(ctx, qp.Name, qp.City, qp.Tags, qp.TypeOf, qp.Available, qp.Page, qp.Limit) + page := engine.RenderRoute(gossr.RenderConfig{ File: "pages/Lending.tsx", Title: "TechAgenda", @@ -30,7 +45,7 @@ func NewLendingHandler(server *echo.Echo, eventService event.Service, engine *ss }, Props: &ssr.Props{ Events: events, - User: userPtr, + User: user.GetUserFromCtx(ctx), }, }) return c.HTML(http.StatusOK, string(page)) diff --git a/pkg/user/middleware.go b/pkg/user/middleware.go index 0ff91a6..70a4bd6 100644 --- a/pkg/user/middleware.go +++ b/pkg/user/middleware.go @@ -37,3 +37,11 @@ func AuthMiddleware(service Service) echo.MiddlewareFunc { } } } + +func GetUserFromCtx(ctx context.Context) *User { + var userPtr *User + if userData, ok := ctx.Value(MiddlewareUserKey).(User); ok { + userPtr = &userData + } + return userPtr +}