forked from nyaruka/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
label.go
95 lines (77 loc) · 2.4 KB
/
label.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
package flows
import (
"encoding/json"
"strings"
"github.com/nyaruka/goflow/utils"
)
// Label represents a message label
type Label struct {
uuid LabelUUID
name string
}
// NewLabel creates a new label given the passed in uuid and name
func NewLabel(uuid LabelUUID, name string) *Label {
return &Label{uuid, name}
}
// UUID returns the UUID of this label
func (l *Label) UUID() LabelUUID { return l.uuid }
// Name returns the name of this label
func (l *Label) Name() string { return l.name }
// Reference returns a reference to this label
func (l *Label) Reference() *LabelReference { return NewLabelReference(l.uuid, l.name) }
// LabelSet defines the unordered set of all labels for a session
type LabelSet struct {
labels []*Label
labelsByUUID map[LabelUUID]*Label
}
// NewLabelSet creates a new label set from the given slice of labels
func NewLabelSet(labels []*Label) *LabelSet {
s := &LabelSet{labels: labels, labelsByUUID: make(map[LabelUUID]*Label, len(labels))}
for _, label := range s.labels {
s.labelsByUUID[label.uuid] = label
}
return s
}
// FindByUUID finds the label with the given UUID
func (s *LabelSet) FindByUUID(uuid LabelUUID) *Label {
return s.labelsByUUID[uuid]
}
// FindByName looks for a label with the given name (case-insensitive)
func (s *LabelSet) FindByName(name string) *Label {
name = strings.ToLower(name)
for _, label := range s.labels {
if strings.ToLower(label.name) == name {
return label
}
}
return nil
}
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type labelEnvelope struct {
UUID LabelUUID `json:"uuid" validate:"required,uuid4"`
Name string `json:"name"`
}
// ReadLabel reads a label from the given JSON
func ReadLabel(data json.RawMessage) (*Label, error) {
var le labelEnvelope
if err := utils.UnmarshalAndValidate(data, &le, "label"); err != nil {
return nil, err
}
return NewLabel(le.UUID, le.Name), nil
}
// ReadLabelSet reads a label set from the given JSON
func ReadLabelSet(data json.RawMessage) (*LabelSet, error) {
items, err := utils.UnmarshalArray(data)
if err != nil {
return nil, err
}
labels := make([]*Label, len(items))
for d := range items {
if labels[d], err = ReadLabel(items[d]); err != nil {
return nil, err
}
}
return NewLabelSet(labels), nil
}