From 1ed88efa0663d7f6e6fa795bb46e67f7021d8b21 Mon Sep 17 00:00:00 2001 From: Shubham Singh Date: Wed, 18 Sep 2024 11:10:25 +0000 Subject: [PATCH] added api for handling transfer Signed-off-by: GitHub --- api/server.go | 2 ++ api/transfer.go | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 api/transfer.go diff --git a/api/server.go b/api/server.go index 0b9929b..91ace35 100644 --- a/api/server.go +++ b/api/server.go @@ -18,6 +18,8 @@ func NewServer(store db.Store) *Server { router.GET("/accounts/:id", server.getAccount) router.GET("/accounts", server.listAccount) + router.POST("/transfers", server.createTransfer) + server.router = router return server } diff --git a/api/transfer.go b/api/transfer.go new file mode 100644 index 0000000..600cfcf --- /dev/null +++ b/api/transfer.go @@ -0,0 +1,71 @@ +package api + +import ( + "database/sql" + "fmt" + "net/http" + + db "github.com/1shubham7/bank/db/sqlc" + "github.com/gin-gonic/gin" +) + +type transferRequest struct { + FromAccountID int64 `json:"from_account_id" binding:"required,min=1"` + ToAccountID int64 `json:"to_account_id" binding:"required,min=1"` + Amount int64 `json:"amount" binding:"required,gt=0"` + Currency string `json:"currency" binding:"required,oneof=USD INR EUR CAD YUAN"` +} + +func (server *Server) createTransfer(ctx *gin.Context) { + var req transferRequest + + err := ctx.ShouldBindJSON(&req) + if err != nil { + ctx.JSON(http.StatusBadRequest, errorResponse(err)) + return + } + + if !server.validAccount(ctx, req.FromAccountID, req.Currency){ + return + } + + if !server.validAccount(ctx, req.ToAccountID, req.Currency){ + return + } + + arg := db.TransferTransectionParams{ + FromAccountID: req.FromAccountID, + ToAccountID: req.ToAccountID, + Amount: req.Amount, + } + + transferTransectionResult, err := server.store.TransferTransection(ctx, arg) + + if err != nil { + ctx.JSON(http.StatusInternalServerError, errorResponse(err)) + return + } + + ctx.JSON(http.StatusOK, transferTransectionResult) +} + +func (server *Server) validAccount(ctx *gin.Context, accountID int64, currency string) (bool) { + account, err := server.store.GetAccount(ctx, accountID) + if err != nil { + if err == sql.ErrNoRows { + ctx.JSON(http.StatusNotFound, errorResponse(err)) + return false + } + + ctx.JSON(http.StatusInternalServerError, errorResponse(err)) + return false + } + + if account.Currency != currency { + err := fmt.Errorf("account [%d] currency mismatch: %s vs %s", account.ID, account.Currency, currency) + ctx.JSON(http.StatusBadRequest, errorResponse(err)) + return false + } + + return true +} \ No newline at end of file