This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
event.go
98 lines (82 loc) · 2.01 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
package state
import (
"github.com/hyperledger/fabric-chaincode-go/shim"
"github.com/s7techlab/cckit/convert"
)
type (
// Event interface for working with events in chaincode
Event interface {
Set(entry interface{}, value ...interface{}) error
UseSetTransformer(ToBytesTransformer) Event
UseNameTransformer(StringTransformer) Event
}
Namer interface {
Name() (string, error)
}
// NameValue interface combines Name() as ToByter methods - event representation
NameValue interface {
Namer
convert.ToByter
}
EventImpl struct {
stub shim.ChaincodeStubInterface
NameTransformer StringTransformer
SetTransformer ToBytesTransformer
}
)
// NewEvent creates wrapper on shim.ChaincodeStubInterface for working with events
func NewEvent(stub shim.ChaincodeStubInterface) *EventImpl {
return &EventImpl{
stub: stub,
NameTransformer: NameAsIs,
SetTransformer: ConvertToBytes,
}
}
func (e *EventImpl) UseSetTransformer(tb ToBytesTransformer) Event {
e.SetTransformer = tb
return e
}
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.SetTransformer(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
}