/
transaction-controller.go
92 lines (79 loc) · 2.73 KB
/
transaction-controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/nashirkra/Ticketing-Applications/helper"
"github.com/nashirkra/Ticketing-Applications/service"
"github.com/nashirkra/Ticketing-Applications/valueObjects"
)
type TransactionController interface {
Create(ctx *gin.Context)
Update(ctx *gin.Context)
}
type transactionController struct {
transationService service.TransactionService
userService service.UserService
jwtService service.JWTService
}
func NewTransactionController(trxServ service.TransactionService, userServ service.UserService, jwtServ service.JWTService) TransactionController {
return &transactionController{
transationService: trxServ,
userService: userServ,
jwtService: jwtServ,
}
}
func (c *transactionController) Create(ctx *gin.Context) {
var createdVO valueObjects.Transaction
err := ctx.ShouldBindJSON(&createdVO)
if err != nil {
response := helper.BuildErrorResponse("Failed to process request", err.Error(), helper.EmptyObj{})
ctx.AbortWithStatusJSON(http.StatusBadRequest, response)
return
} else {
authHeader := ctx.GetHeader("Authorization")
token, errToken := c.jwtService.ValidateToken(authHeader)
if errToken != nil {
panic(errToken.Error())
}
claims := token.Claims.(jwt.MapClaims)
userID := fmt.Sprintf("%v", claims["user_id"])
createdVO.CreatorId, _ = strconv.Atoi(userID)
result, err := c.transationService.Create(createdVO)
if err != nil {
response := helper.BuildErrorResponse("Failed to Create Transaction", err.Error(), helper.EmptyObj{})
ctx.AbortWithStatusJSON(http.StatusBadRequest, response)
return
}
response := helper.BuildResponse(true, "OK", result)
ctx.JSON(http.StatusCreated, response)
}
}
func (c *transactionController) Update(ctx *gin.Context) {
var updateVO valueObjects.Transaction
err := ctx.ShouldBindJSON(&updateVO)
if err != nil {
response := helper.BuildErrorResponse("Failed to process request", err.Error(), helper.EmptyObj{})
ctx.AbortWithStatusJSON(http.StatusBadRequest, response)
return
} else {
authHeader := ctx.GetHeader("Authorization")
token, errToken := c.jwtService.ValidateToken(authHeader)
if errToken != nil {
panic(errToken.Error())
}
claims := token.Claims.(jwt.MapClaims)
userID := fmt.Sprintf("%v", claims["user_id"])
updateVO.CreatorId, _ = strconv.Atoi(userID)
result, err := c.transationService.Update(updateVO)
if err != nil {
response := helper.BuildErrorResponse("Failed to Create Transaction", err.Error(), helper.EmptyObj{})
ctx.AbortWithStatusJSON(http.StatusBadRequest, response)
return
}
response := helper.BuildResponse(true, "OK", result)
ctx.JSON(http.StatusCreated, response)
}
}