-
Notifications
You must be signed in to change notification settings - Fork 19
/
base.go
63 lines (48 loc) · 1.9 KB
/
base.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
package events
import (
"encoding/json"
"time"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/utils"
"github.com/nyaruka/goflow/utils/dates"
"github.com/pkg/errors"
)
var registeredTypes = map[string](func() flows.Event){}
// RegisterType registers a new type of router
func RegisterType(name string, initFunc func() flows.Event) {
registeredTypes[name] = initFunc
}
// BaseEvent is the base of all event types
type BaseEvent struct {
Type_ string `json:"type" validate:"required"`
CreatedOn_ time.Time `json:"created_on" validate:"required"`
StepUUID_ flows.StepUUID `json:"step_uuid,omitempty" validate:"omitempty,uuid4"`
}
// NewBaseEvent creates a new base event
func NewBaseEvent(typeName string) BaseEvent {
return BaseEvent{Type_: typeName, CreatedOn_: dates.Now()}
}
// Type returns the type of this event
func (e *BaseEvent) Type() string { return e.Type_ }
// CreatedOn returns the created on time of this event
func (e *BaseEvent) CreatedOn() time.Time { return e.CreatedOn_ }
// StepUUID returns the UUID of the step in the path where this event occured
func (e *BaseEvent) StepUUID() flows.StepUUID { return e.StepUUID_ }
// SetStepUUID sets the UUID of the step in the path where this event occured
func (e *BaseEvent) SetStepUUID(stepUUID flows.StepUUID) { e.StepUUID_ = stepUUID }
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
// ReadEvent reads a single event from the given JSON
func ReadEvent(data json.RawMessage) (flows.Event, error) {
typeName, err := utils.ReadTypeFromJSON(data)
if err != nil {
return nil, err
}
f := registeredTypes[typeName]
if f == nil {
return nil, errors.Errorf("unknown type: '%s'", typeName)
}
event := f()
return event, utils.UnmarshalAndValidate(data, event)
}