-
Notifications
You must be signed in to change notification settings - Fork 189
/
settings.go
92 lines (74 loc) · 1.97 KB
/
settings.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
85
86
87
88
89
90
91
92
package admin
import (
"encoding/json"
"fmt"
"github.com/jinzhu/gorm"
"github.com/qor/qor"
)
// SettingsStorageInterface settings storage interface
type SettingsStorageInterface interface {
Get(key string, value interface{}, context *Context) error
Save(key string, value interface{}, res *Resource, user qor.CurrentUser, context *Context) error
}
func newSettings(db *gorm.DB) SettingsStorageInterface {
if db != nil {
db.AutoMigrate(&QorAdminSetting{})
}
return settings{}
}
// QorAdminSetting admin settings
type QorAdminSetting struct {
gorm.Model
Key string
Resource string
UserID string
Value string `gorm:"size:65532"`
}
type settings struct{}
// Get load admin settings
func (settings) Get(key string, value interface{}, context *Context) error {
var (
settings = []QorAdminSetting{}
tx = context.GetDB().New()
resParams = ""
userID = ""
)
sqlCondition := fmt.Sprintf("%v = ? AND (resource = ? OR resource = ?) AND (user_id = ? OR user_id = ?)", tx.NewScope(nil).Quote("key"))
if context.Resource != nil {
resParams = context.Resource.ToParam()
}
if context.CurrentUser != nil {
userID = ""
}
tx.Where(sqlCondition, key, resParams, "", userID, "").Order("user_id DESC, resource DESC, id DESC").Find(&settings)
for _, setting := range settings {
if err := json.Unmarshal([]byte(setting.Value), value); err != nil {
return err
}
}
return nil
}
// Save save admin settings
func (settings) Save(key string, value interface{}, res *Resource, user qor.CurrentUser, context *Context) error {
var (
tx = context.GetDB().New()
result, err = json.Marshal(value)
resParams = ""
userID = ""
)
if err != nil {
return err
}
if res != nil {
resParams = res.ToParam()
}
if user != nil {
userID = ""
}
err = tx.Where(QorAdminSetting{
Key: key,
UserID: userID,
Resource: resParams,
}).Assign(QorAdminSetting{Value: string(result)}).FirstOrCreate(&QorAdminSetting{}).Error
return err
}