Skip to content

Commit

Permalink
Refactor query processing and user retrieval
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
caioeverest committed Jan 29, 2024
1 parent 09825d9 commit f60736d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
25 changes: 20 additions & 5 deletions pkg/lending/handler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lending

import (
"log/slog"
"net/http"

"github.com/labstack/echo/v4"
Expand All @@ -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",
Expand All @@ -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))
Expand Down
8 changes: 8 additions & 0 deletions pkg/user/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit f60736d

Please sign in to comment.