-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
chains_controller.go
86 lines (71 loc) · 2.16 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
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/chains"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/logger/audit"
)
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 {
resourceName string
chainSet chains.Chains
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](prefix string, chainSet chains.Chains, errNotEnabled error,
newResource func(types.ChainStatus) R, lggr logger.Logger, auditLogger audit.AuditLogger) *chainsController[R] {
return &chainsController[R]{
resourceName: prefix + "_chain",
chainSet: chainSet,
errNotEnabled: errNotEnabled,
newResource: newResource,
lggr: lggr,
auditLogger: auditLogger,
}
}
func (cc *chainsController[R]) Index(c *gin.Context, size, page, offset int) {
if cc.chainSet == nil {
jsonAPIError(c, http.StatusBadRequest, cc.errNotEnabled)
return
}
chains, count, err := cc.chainSet.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.chainSet == nil {
jsonAPIError(c, http.StatusBadRequest, cc.errNotEnabled)
return
}
chain, err := cc.chainSet.ChainStatus(c, c.Param("ID"))
if err != nil {
jsonAPIError(c, http.StatusBadRequest, err)
return
}
jsonAPIResponse(c, cc.newResource(chain), cc.resourceName)
}