-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
95 lines (82 loc) · 2.34 KB
/
transaction.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
93
94
95
package handlers
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
egateway "github.com/gsstoykov/go-ethereum-fetcher/ethereum"
"github.com/gsstoykov/go-ethereum-fetcher/model"
"github.com/gsstoykov/go-ethereum-fetcher/repository"
)
type TransactionHandler struct {
tr repository.ITransactionRepository
ur repository.IUserRepository
eg egateway.IEthereumGateway
}
func NewTransactionHandler(tr repository.ITransactionRepository, ur repository.IUserRepository, eg egateway.IEthereumGateway) *TransactionHandler {
return &TransactionHandler{
tr: tr,
ur: ur,
eg: eg,
}
}
func (th TransactionHandler) FetchTransactions(ctx *gin.Context) {
var ts []model.Transaction
ts, err := th.tr.FindAll()
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"transactions": ts})
}
func (th TransactionHandler) FetchTransactionsList(ctx *gin.Context) {
// Get the list of transactionHashes
txHashes := ctx.QueryArray("transactionHashes")
username, _ := ctx.Get("username")
user, err := th.ur.FindByUsername(fmt.Sprint(username))
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var txs []model.Transaction
// Fetch for all transactionHashes
for _, txHash := range txHashes {
tx, err := th.tr.FindByTransactionHash(txHash)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if tx == nil {
tx, err = th.eg.GetByTransactionHash(txHash)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
tx, err = th.tr.Create(tx)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
}
if user != nil {
err = th.ur.AddTransactionToUser(*user, *tx)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
txs = append(txs, *tx)
}
ctx.JSON(http.StatusOK, gin.H{"transactions": txs})
}
func (th TransactionHandler) CreateTransaction(ctx *gin.Context) {
var t model.Transaction
if err := ctx.ShouldBindJSON(&t); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ct, err := th.tr.Create(&t)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusCreated, gin.H{"transaction": ct})
}