-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
event.go
56 lines (48 loc) · 1.04 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
package events
import (
"encoding/json"
"fmt"
"strings"
)
// Event represents different events
// in the lifecycle of a Buffalo app
type Event struct {
// Kind is the "type" of event "app:start"
Kind string `json:"kind"`
// Message is optional
Message string `json:"message"`
// Payload is optional
Payload Payload `json:"payload"`
// Error is optional
Error error `json:"-"`
}
func (e Event) String() string {
b, _ := e.MarshalJSON()
return string(b)
}
// MarshalJSON implements the json marshaler for an event
func (e Event) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"kind": e.Kind,
}
if len(e.Message) != 0 {
m["message"] = e.Message
}
if e.Error != nil {
m["error"] = e.Error.Error()
}
if len(e.Payload) != 0 {
m["payload"] = e.Payload
}
return json.Marshal(m)
}
// Validate that an event is ready to be emitted
func (e Event) Validate() error {
if len(e.Kind) == 0 {
return fmt.Errorf("kind can not be blank")
}
return nil
}
func (e Event) IsError() bool {
return strings.HasSuffix(e.Kind, ":err")
}