From 7b8405abddb2362889f8d447b4c4becf5fb9f45d Mon Sep 17 00:00:00 2001 From: qowevisa Date: Sun, 10 Nov 2024 08:25:35 +0200 Subject: [PATCH] Small refactoring and adding getting all handler to cards --- handlers/card.go | 50 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/handlers/card.go b/handlers/card.go index caad4dc..21acb09 100644 --- a/handlers/card.go +++ b/handlers/card.go @@ -6,6 +6,16 @@ import ( "github.com/gin-gonic/gin" ) +var cardTransform func(inp *db.Card) types.DbCard = func(inp *db.Card) types.DbCard { + return types.DbCard{ + ID: inp.ID, + Name: inp.Name, + Balance: inp.Balance, + HaveCreditLine: inp.HaveCreditLine, + CreditLine: inp.CreditLine, + } +} + // @Summary Get card by id // @Description Get card by id // @Tags card @@ -20,15 +30,37 @@ import ( // @Security ApiKeyAuth // @Router /card/:id [get] func CardGetId(c *gin.Context) { - GetHandler(func(inp *db.Card) types.DbCard { - return types.DbCard{ - ID: inp.ID, - Name: inp.Name, - Balance: inp.Balance, - HaveCreditLine: inp.HaveCreditLine, - CreditLine: inp.CreditLine, - } - })(c) + GetHandler(cardTransform)(c) +} + +// @Summary Get all cards for user +// @Description Get all cards for user +// @Tags card +// @Produce json +// @Param Authorization header string true "Bearer token" +// @Success 200 {object} []types.DbCard +// @Failure 401 {object} types.ErrorResponse +// @Failure 500 {object} types.ErrorResponse +// @Security ApiKeyAuth +// @Router /card/all [get] +func CardGetAll(c *gin.Context) { + userID, err := GetUserID(c) + if err != nil { + c.JSON(500, types.ErrorResponse{Message: err.Error()}) + return + } + dbc := db.Connect() + var entities []*db.Card + if err := dbc.Find(&entities, db.Card{UserID: userID}).Error; err != nil { + c.JSON(500, types.ErrorResponse{Message: err.Error()}) + return + } + + var ret []types.DbCard + for _, entity := range entities { + ret = append(ret, cardTransform(entity)) + } + c.JSON(200, ret) } // @Summary Get card by id