forked from AndrewBurian/eventsource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_factory.go
79 lines (69 loc) · 1.67 KB
/
event_factory.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
package eventsource
import (
"io"
"strconv"
)
// EventFactory is a type of object that can create new events
type EventFactory interface {
New() *Event
}
// EventIDFactory is an event factory that creates events with
// sequential ID fields.
// If NewFunc is set, the factory uses it to create events before setting
// their IDs
// If NewFunc is not set, NewFact will be used. If neither is set, a new
// event is created from scratch
type EventIDFactory struct {
NewFact EventFactory
NewFunc func() *Event
Next uint64
}
// New creates an event with the Next id in the sequence
func (f *EventIDFactory) New() *Event {
var e *Event
if f.NewFunc != nil {
e = f.NewFunc()
} else if f.NewFact != nil {
e = f.NewFact.New()
} else {
e = &Event{}
}
e.id = strconv.FormatUint(f.Next, 10)
f.Next++
return e
}
// EventTypeFactory creates events of a specific type
type EventTypeFactory struct {
NewFact EventFactory
NewFunc func() *Event
Type string
}
// New creates an event with the event type set
// If NewFunc is set, the factory uses it to create events before setting
// their event types
// If NewFunc is not set, NewFact will be used. If neither is set, a new
// event is created from scratch
func (f *EventTypeFactory) New() *Event {
var e *Event
if f.NewFunc != nil {
e = f.NewFunc()
} else if f.NewFact != nil {
e = f.NewFact.New()
} else {
e = &Event{}
}
e.event = f.Type
return e
}
// DataEvent creates a new Event with the data field set
func DataEvent(data string) *Event {
e := &Event{}
io.WriteString(e, data)
return e
}
// TypeEvent creates a new Event with the event field set
func TypeEvent(t string) *Event {
return &Event{
event: t,
}
}