Skip to content

Commit

Permalink
added api for handling transfer
Browse files Browse the repository at this point in the history
Signed-off-by: GitHub <[email protected]>
  • Loading branch information
1Shubham7 authored Sep 18, 2024
1 parent 523b3f9 commit 1ed88ef
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
2 changes: 2 additions & 0 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
71 changes: 71 additions & 0 deletions api/transfer.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 1ed88ef

Please sign in to comment.