OSDN Git Service

refactor(federation): change filter in list-txs (#221)
[bytom/vapor.git] / federation / api / handler.go
1 package api
2
3 import (
4         "database/sql"
5         "fmt"
6
7         "github.com/gin-gonic/gin"
8
9         "github.com/vapor/errors"
10         "github.com/vapor/federation/common"
11         "github.com/vapor/federation/database/orm"
12 )
13
14 type listCrosschainTxsReq struct{ Display }
15
16 func (s *Server) ListCrosschainTxs(c *gin.Context, listTxsReq *listCrosschainTxsReq, query *PaginationQuery) ([]*orm.CrossTransaction, error) {
17         var ormTxs []*orm.CrossTransaction
18         txFilter := &orm.CrossTransaction{}
19
20         // filter tx status
21         if status, err := listTxsReq.GetFilterString("status"); err == nil && status != "" {
22                 switch status {
23                 case "pending":
24                         txFilter.Status = common.CrossTxPendingStatus
25                 case "completed":
26                         txFilter.Status = common.CrossTxCompletedStatus
27                 }
28         }
29
30         // filter tx hash
31         if txHash, err := listTxsReq.GetFilterString("source_tx_hash"); err == nil && txHash != "" {
32                 txFilter.SourceTxHash = txHash
33         }
34         if txHash, err := listTxsReq.GetFilterString("dest_tx_hash"); err == nil && txHash != "" {
35                 txFilter.DestTxHash = sql.NullString{txHash, true}
36         }
37
38         txQuery := s.db.Preload("Chain").Preload("Reqs").Preload("Reqs.Asset").Where(txFilter)
39         // filter direction
40         if fromChainName, err := listTxsReq.GetFilterString("from"); err == nil && fromChainName != "" {
41                 txQuery = txQuery.Joins("join chains on chains.id = cross_transactions.chain_id").Where("chains.name = ?", fromChainName)
42         }
43         txQuery = txQuery.Order(fmt.Sprintf("cross_transactions.source_block_height %s", listTxsReq.Sorter.Order))
44         txQuery = txQuery.Order(fmt.Sprintf("cross_transactions.source_tx_index %s", listTxsReq.Sorter.Order))
45         if err := txQuery.Offset(query.Start).Limit(query.Limit).Find(&ormTxs).Error; err != nil {
46                 return nil, errors.Wrap(err, "query txs")
47         }
48
49         return ormTxs, nil
50 }