This repository was archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathevent.go
78 lines (65 loc) · 1.49 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package models
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
// Event represents an action in the system.
// In general, the event generates for a subject
// of the form: type.action.key
//
// swagger:model
type Event struct {
// Time of the event.
// swagger:strfmt date-time
Time time.Time
// Type - object type
Type string
// Action - what happened
Action string
// Key - the id of the object
Key string
// Principal - the user or subsystem that caused the event to be emitted
Principal string
// Object - the data of the object.
Object interface{}
// Original - the data of the object before the operation (update and save only)
Original interface{}
}
func (e *Event) Text() string {
jsonString, err := json.MarshalIndent(e.Object, "", " ")
if err != nil {
jsonString = []byte("json failure")
}
return fmt.Sprintf("%d: %s %s %s %s\n%s\n", e.Time.Unix(), e.Type, e.Action, e.Key, e.Principal, string(jsonString))
}
func (e *Event) Model() (Model, error) {
res, err := New(e.Type)
if err != nil {
return nil, err
}
buf := bytes.Buffer{}
enc, dec := json.NewEncoder(&buf), json.NewDecoder(&buf)
err = enc.Encode(e.Object)
if err != nil {
return nil, err
}
err = dec.Decode(res)
return res, err
}
func (e *Event) Message() string {
if s, ok := e.Object.(string); ok {
return s
}
return ""
}
func EventFor(obj Model, action string) *Event {
return &Event{
Time: time.Now(),
Type: obj.Prefix(),
Action: action,
Key: obj.Key(),
Object: obj,
}
}