forked from nyaruka/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resthook.go
83 lines (65 loc) · 2.21 KB
/
resthook.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
package flows
import (
"encoding/json"
"github.com/nyaruka/goflow/utils"
)
// Resthook represents a named event and a set of subscribers
type Resthook struct {
slug string
subscribers []string
}
// NewResthook returns a new resthook object
func NewResthook(slug string, subscribers []string) *Resthook {
return &Resthook{slug: slug, subscribers: subscribers}
}
// Slug returns the slug of the resthook
func (r *Resthook) Slug() string { return r.slug }
// Subscribers returns the subscribers to the resthook
func (r *Resthook) Subscribers() []string { return r.subscribers }
// ResthookSet defines the unordered set of all resthooks for a session
type ResthookSet struct {
resthooksBySlug map[string]*Resthook
}
// NewResthookSet creates a new resthook set from the given list of resthooks
func NewResthookSet(resthooks []*Resthook) *ResthookSet {
s := &ResthookSet{
resthooksBySlug: make(map[string]*Resthook, len(resthooks)),
}
for _, resthook := range resthooks {
s.resthooksBySlug[resthook.slug] = resthook
}
return s
}
// FindBySlug finds the group with the given UUID
func (s *ResthookSet) FindBySlug(slug string) *Resthook {
return s.resthooksBySlug[slug]
}
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type resthookEnvelope struct {
Slug string `json:"slug" validate:"required"`
Subscribers []string `json:"subscribers" validate:"required,dive,url"`
}
// ReadResthook reads a resthook from the given JSON
func ReadResthook(data json.RawMessage) (*Resthook, error) {
var e resthookEnvelope
if err := utils.UnmarshalAndValidate(data, &e, "resthook"); err != nil {
return nil, err
}
return NewResthook(e.Slug, e.Subscribers), nil
}
// ReadResthookSet reads a resthook set from the given JSON
func ReadResthookSet(data json.RawMessage) (*ResthookSet, error) {
items, err := utils.UnmarshalArray(data)
if err != nil {
return nil, err
}
resthooks := make([]*Resthook, len(items))
for d := range items {
if resthooks[d], err = ReadResthook(items[d]); err != nil {
return nil, err
}
}
return NewResthookSet(resthooks), nil
}