-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
77 lines (65 loc) · 1.84 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
package publish
import (
"errors"
"fmt"
"github.com/jinzhu/gorm"
)
type EventInterface interface {
Publish(db *gorm.DB, event PublishEventInterface) error
Discard(db *gorm.DB, event PublishEventInterface) error
}
var events = map[string]EventInterface{}
func RegisterEvent(name string, event EventInterface) {
events[name] = event
}
type PublishEvent struct {
gorm.Model
Name string
Description string
Argument string `sql:"size:65532"`
PublishStatus bool
PublishedBy string
}
func getCurrentUser(db *gorm.DB) (string, bool) {
if user, hasUser := db.Get("qor:current_user"); hasUser {
var currentUser string
if primaryField := db.NewScope(user).PrimaryField(); primaryField != nil {
currentUser = fmt.Sprintf("%v", primaryField.Field.Interface())
} else {
currentUser = fmt.Sprintf("%v", user)
}
return currentUser, true
}
return "", false
}
func (publishEvent *PublishEvent) Publish(db *gorm.DB) error {
if event, ok := events[publishEvent.Name]; ok {
err := event.Publish(db, publishEvent)
if err == nil {
var updateAttrs = map[string]interface{}{"PublishStatus": PUBLISHED}
if user, hasUser := getCurrentUser(db); hasUser {
updateAttrs["PublishedBy"] = user
}
err = db.Model(publishEvent).Update(updateAttrs).Error
}
return err
}
return errors.New("event not found")
}
func (publishEvent *PublishEvent) Discard(db *gorm.DB) error {
if event, ok := events[publishEvent.Name]; ok {
err := event.Discard(db, publishEvent)
if err == nil {
var updateAttrs = map[string]interface{}{"PublishStatus": PUBLISHED}
if user, hasUser := getCurrentUser(db); hasUser {
updateAttrs["PublishedBy"] = user
}
err = db.Model(publishEvent).Update(updateAttrs).Error
}
return err
}
return errors.New("event not found")
}
func (PublishEvent) VisiblePublishResource() bool {
return true
}