From 85f624952ed0b37225165f8b9e8a8613e3b1ff74 Mon Sep 17 00:00:00 2001 From: Luis Angel Arvelo Date: Tue, 3 Oct 2023 03:53:00 +0000 Subject: [PATCH] Create account request handlers --- api/account.go | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 api/account.go diff --git a/api/account.go b/api/account.go new file mode 100644 index 0000000..d1bf00d --- /dev/null +++ b/api/account.go @@ -0,0 +1,87 @@ +package api + +import ( + "errors" + "net/http" + + db "github.com/Delavalom/RBD/db/sqlc" + "github.com/gin-gonic/gin" +) + +type createAccountRequest struct { + Owner string `json:"owner" binding:"required"` + Currency string `json:"currency" binding:"required,oneof=DOP USD EUR"` +} + +func (server *Server) createAccount(ctx *gin.Context) { + var req createAccountRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + ctx.JSON(http.StatusBadRequest, errorResponse(err)) + return + } + + arg := db.CreateAccountParams{ + Owner: req.Owner, + Currency: req.Currency, + Balance: 0, + } + account, err := server.store.CreateAccount(ctx, arg) + if err != nil { + ctx.JSON(http.StatusInternalServerError, errorResponse(err)) + return + } + ctx.JSON(http.StatusOK, account) +} + +type getAccountRequest struct { + ID int64 `uri:"id" binding:"required,min=1"` +} + +func (server *Server) getAccount(ctx *gin.Context) { + var req getAccountRequest + if err := ctx.ShouldBindUri(&req); err != nil { + ctx.JSON(http.StatusBadRequest, errorResponse(err)) + return + } + account, err := server.store.GetAccount(ctx, req.ID) + if err != nil { + if errors.Is(err, db.ErrRecordNotFound) { + ctx.JSON(http.StatusNotFound, errorResponse(err)) + return + } + ctx.JSON(http.StatusInternalServerError, errorResponse(err)) + return + } + + ctx.JSON(http.StatusOK, account) +} + +type listAccountRequest struct { + PageID int32 `form:"page_id" binding:"required,min=1"` + PageSize int32 `form:"page_size" binding:"required,min=5,max=10"` +} + +func (server *Server) listAccount(ctx *gin.Context) { + var req listAccountRequest + if err := ctx.ShouldBindQuery(&req); err != nil { + ctx.JSON(http.StatusBadRequest, errorResponse(err)) + return + } + + arg := db.ListAccountsParams{ + Owner: "Luis", + Limit: req.PageSize, + Offset: (req.PageID - 1) * req.PageSize, + } + accounts, err := server.store.ListAccounts(ctx, arg) + if err != nil { + if errors.Is(err, db.ErrRecordNotFound) { + ctx.JSON(http.StatusNotFound, errorResponse(err)) + return + } + ctx.JSON(http.StatusInternalServerError, errorResponse(err)) + return + } + + ctx.JSON(http.StatusOK, accounts) +}