mirror of https://github.com/grafana/grafana
parent
dace35d31d
commit
525179eb85
@ -1,8 +1,63 @@ |
||||
package events |
||||
|
||||
import ( |
||||
"reflect" |
||||
"time" |
||||
) |
||||
|
||||
// Events can be passed to external systems via for example AMPQ
|
||||
// Treat these events as basically DTOs so changes has to be backward compatible
|
||||
|
||||
type Priority string |
||||
|
||||
const ( |
||||
PRIO_DEBUG Priority = "DEBUG" |
||||
PRIO_INFO Priority = "INFO" |
||||
PRIO_ERROR Priority = "ERROR" |
||||
) |
||||
|
||||
type Event struct { |
||||
Timestamp time.Time `json:"timestamp"` |
||||
} |
||||
|
||||
type OnTheWireEvent struct { |
||||
EventType string `json:"event_type"` |
||||
Priority Priority `json:"priority"` |
||||
Timestamp time.Time `json:"timestamp"` |
||||
Payload interface{} `json:"payload"` |
||||
} |
||||
|
||||
type EventBase interface { |
||||
ToOnWriteEvent() *OnTheWireEvent |
||||
} |
||||
|
||||
func ToOnWriteEvent(event interface{}) (*OnTheWireEvent, error) { |
||||
eventType := reflect.TypeOf(event) |
||||
|
||||
wireEvent := OnTheWireEvent{ |
||||
Priority: PRIO_INFO, |
||||
EventType: eventType.Name(), |
||||
Payload: event, |
||||
} |
||||
|
||||
baseField := reflect.ValueOf(event).FieldByName("Timestamp") |
||||
if baseField.IsValid() { |
||||
wireEvent.Timestamp = baseField.Interface().(time.Time) |
||||
} else { |
||||
wireEvent.Timestamp = time.Now() |
||||
} |
||||
|
||||
return &wireEvent, nil |
||||
} |
||||
|
||||
type AccountCreated struct { |
||||
Name string `json:"name"` |
||||
Timestamp time.Time `json:"timestamp"` |
||||
Id int64 `json:"id"` |
||||
Name string `json:"name"` |
||||
} |
||||
|
||||
type AccountUpdated struct { |
||||
Timestamp time.Time `json:"timestamp"` |
||||
Id int64 `json:"id"` |
||||
Name string `json:"name"` |
||||
} |
||||
|
||||
@ -1,18 +1,30 @@ |
||||
package events |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"testing" |
||||
"time" |
||||
|
||||
. "github.com/smartystreets/goconvey/convey" |
||||
) |
||||
|
||||
type TestEvent struct { |
||||
Timestamp time.Time |
||||
} |
||||
|
||||
func TestEventCreation(t *testing.T) { |
||||
|
||||
Convey("When generating slug", t, func() { |
||||
dashboard := NewDashboard("Grafana Play Home") |
||||
dashboard.UpdateSlug() |
||||
Convey("Event to wire event", t, func() { |
||||
e := TestEvent{ |
||||
Timestamp: time.Unix(1231421123, 223), |
||||
} |
||||
|
||||
wire, _ := ToOnWriteEvent(e) |
||||
So(e.Timestamp.Unix(), ShouldEqual, wire.Timestamp.Unix()) |
||||
So(wire.EventType, ShouldEqual, "TestEvent") |
||||
|
||||
So(dashboard.Slug, ShouldEqual, "grafana-play-home") |
||||
json, _ := json.Marshal(wire) |
||||
So(string(json), ShouldEqual, `{"event_type":"TestEvent","priority":"INFO","timestamp":"2009-01-08T14:25:23.000000223+01:00","payload":{"Timestamp":"2009-01-08T14:25:23.000000223+01:00"}}`) |
||||
}) |
||||
|
||||
} |
||||
|
||||
Loading…
Reference in new issue