-
Notifications
You must be signed in to change notification settings - Fork 6
/
event.go
104 lines (87 loc) · 2.31 KB
/
event.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
96
97
98
99
100
101
102
103
104
package state
import (
"github.com/hyperledger/fabric-chaincode-go/shim"
"github.com/hyperledger-labs/cckit/serialize"
)
type (
// Event interface for working with events in chaincode
Event interface {
Set(entry interface{}, value ...interface{}) error
UseToBytesConverter(serialize.ToBytesConverter) Event
// ToBytesConverter todo: check neediness
ToBytesConverter() serialize.ToBytesConverter
UseNameTransformer(StringTransformer) Event
}
Namer interface {
Name() (string, error)
}
// NameValue interface combines Name() as ToByter methods - event representation
NameValue interface {
Namer
serialize.ToBytesConverter
}
EventImpl struct {
stub shim.ChaincodeStubInterface
nameTransformer StringTransformer
toBytesConverter serialize.ToBytesConverter
}
)
// NewEvent creates wrapper on shim.ChaincodeStubInterface for working with events
func NewEvent(stub shim.ChaincodeStubInterface) *EventImpl {
return &EventImpl{
stub: stub,
nameTransformer: NameAsIs,
toBytesConverter: serialize.DefaultSerializer,
}
}
func (e *EventImpl) UseToBytesConverter(toBytesConverter serialize.ToBytesConverter) Event {
e.toBytesConverter = toBytesConverter
return e
}
func (e *EventImpl) ToBytesConverter() serialize.ToBytesConverter {
return e.toBytesConverter
}
func (e *EventImpl) UseNameTransformer(nt StringTransformer) Event {
e.nameTransformer = nt
return e
}
func (e *EventImpl) Set(entry interface{}, values ...interface{}) error {
name, value, err := e.ArgNameValue(entry, values)
if err != nil {
return err
}
nameStr, err := e.nameTransformer(name)
if err != nil {
return err
}
bb, err := e.toBytesConverter.ToBytesFrom(value)
if err != nil {
return err
}
return e.stub.SetEvent(nameStr, bb)
}
func (e *EventImpl) ArgNameValue(arg interface{}, values []interface{}) (name string, value interface{}, err error) {
// name must be
name, err = NormalizeEventName(arg)
if err != nil {
return
}
switch len(values) {
// arg is name and value
case 0:
return name, arg, nil
case 1:
return name, values[0], nil
default:
return ``, nil, ErrAllowOnlyOneValue
}
}
func NormalizeEventName(name interface{}) (string, error) {
switch n := name.(type) {
case Namer:
return n.Name()
case string:
return n, nil
}
return ``, ErrUnableToCreateEventName
}