-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
chains_controller.go
90 lines (75 loc) · 2.42 KB
/
chains_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
package web
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/manyminds/api2go/jsonapi"
"github.com/smartcontractkit/chainlink-relay/pkg/types"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/logger/audit"
"github.com/smartcontractkit/chainlink/v2/core/services/chainlink"
"github.com/smartcontractkit/chainlink/v2/core/services/relay"
)
type ChainsController interface {
// Index lists chains.
Index(c *gin.Context, size, page, offset int)
// Show gets a chain by id.
Show(*gin.Context)
}
type chainsController[R jsonapi.EntityNamer] struct {
network relay.Network
resourceName string
chainStats chainlink.ChainStatuser
errNotEnabled error
newResource func(types.ChainStatus) R
lggr logger.Logger
auditLogger audit.AuditLogger
}
type errChainDisabled struct {
name string
tomlKey string
}
func (e errChainDisabled) Error() string {
return fmt.Sprintf("%s is disabled: Set %s=true to enable", e.name, e.tomlKey)
}
func newChainsController[R jsonapi.EntityNamer](network relay.Network, chainStats chainlink.ChainsNodesStatuser, errNotEnabled error,
newResource func(types.ChainStatus) R, lggr logger.Logger, auditLogger audit.AuditLogger) *chainsController[R] {
return &chainsController[R]{
network: network,
resourceName: string(network) + "_chain",
chainStats: chainStats,
errNotEnabled: errNotEnabled,
newResource: newResource,
lggr: lggr,
auditLogger: auditLogger,
}
}
func (cc *chainsController[R]) Index(c *gin.Context, size, page, offset int) {
if cc.chainStats == nil {
jsonAPIError(c, http.StatusBadRequest, cc.errNotEnabled)
return
}
chains, count, err := cc.chainStats.ChainStatuses(c, offset, size)
if err != nil {
jsonAPIError(c, http.StatusBadRequest, err)
return
}
var resources []R
for _, chain := range chains {
resources = append(resources, cc.newResource(chain))
}
paginatedResponse(c, cc.resourceName, size, page, resources, count, err)
}
func (cc *chainsController[R]) Show(c *gin.Context) {
if cc.chainStats == nil {
jsonAPIError(c, http.StatusBadRequest, cc.errNotEnabled)
return
}
relayID := relay.ID{Network: cc.network, ChainID: relay.ChainID(c.Param("ID"))}
chain, err := cc.chainStats.ChainStatus(c, relayID)
if err != nil {
jsonAPIError(c, http.StatusBadRequest, err)
return
}
jsonAPIResponse(c, cc.newResource(chain), cc.resourceName)
}