-
Notifications
You must be signed in to change notification settings - Fork 29
/
consumer.go
75 lines (62 loc) · 1.6 KB
/
consumer.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
package magmasc
import (
"encoding/json"
"github.com/0chain/gosdk/core/util"
"github.com/0chain/gosdk/zmagmacore/config"
"github.com/0chain/gosdk/zmagmacore/errors"
"github.com/0chain/gosdk/zmagmacore/node"
)
type (
// Consumer represents consumers node stored in blockchain.
Consumer struct {
ID string `json:"id"`
ExtID string `json:"ext_id"`
Host string `json:"host,omitempty"`
}
)
var (
// Make sure Consumer implements Serializable interface.
_ util.Serializable = (*Consumer)(nil)
)
// NewConsumerFromCfg creates Consumer from config.Consumer.
func NewConsumerFromCfg(cfg *config.Consumer) *Consumer {
return &Consumer{
ID: node.ID(),
ExtID: cfg.ExtID,
Host: cfg.Host,
}
}
// Decode implements util.Serializable interface.
func (m *Consumer) Decode(blob []byte) error {
var consumer Consumer
if err := json.Unmarshal(blob, &consumer); err != nil {
return errDecodeData.Wrap(err)
}
if err := consumer.Validate(); err != nil {
return err
}
m.ID = consumer.ID
m.ExtID = consumer.ExtID
m.Host = consumer.Host
return nil
}
// Encode implements util.Serializable interface.
func (m *Consumer) Encode() []byte {
blob, _ := json.Marshal(m)
return blob
}
// GetType returns node type.
func (m *Consumer) GetType() string {
return consumerType
}
// Validate checks the Consumer for correctness.
// If it is not return errInvalidConsumer.
func (m *Consumer) Validate() (err error) {
switch { // is invalid
case m.ExtID == "":
err = errors.New(errCodeBadRequest, "consumer external id is required")
default:
return nil // is valid
}
return errInvalidConsumer.Wrap(err)
}