-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathevent.go
84 lines (72 loc) · 2.16 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
79
80
81
82
83
84
package publish
import (
"errors"
"fmt"
"github.com/jinzhu/gorm"
"github.com/qor/qor"
)
// EventInterface defined methods needs for a publish event
type EventInterface interface {
Publish(db *gorm.DB, event PublishEventInterface) error
Discard(db *gorm.DB, event PublishEventInterface) error
}
var events = map[string]EventInterface{}
// RegisterEvent register publish event
func RegisterEvent(name string, event EventInterface) {
events[name] = event
}
// PublishEvent default publish event model
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
}
// Publish publish data
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")
}
// Discard discard data
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")
}
// VisiblePublishResource force to display publish event in publish drafts even it is hidden in the menus
func (PublishEvent) VisiblePublishResource(*qor.Context) bool {
return true
}