-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
79 lines (66 loc) · 1.51 KB
/
plugin.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
package gcache
import (
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"time"
)
const CacheBeforeQuery = "CACHE:BEFORE_QUERY"
const CacheAfterQuery = "CACHE:AFTER_QUERY"
const CacheOption = "gorm:cache"
//Plugin
type Plugin struct {
cacheDriver CacheDriver
}
//NewPlugin
func NewPlugin(driver CacheDriver) Plugin {
return Plugin{
cacheDriver: driver,
}
}
//Bind
func (p Plugin) Bind(db *gorm.DB) {
db.Callback().Query().Before("gorm:query").Register(CacheBeforeQuery, p.beforeQueryInvoke)
db.Callback().Query().After("gorm:after_query").Register(CacheAfterQuery, p.afterQueryInvoke)
}
func (p Plugin) beforeQueryInvoke(scope *gorm.Scope) {
cacheOption, ok := scope.Get(CacheOption)
if !ok {
return
}
param, ok := cacheOption.(CacheParam)
if !ok {
scope.Log("cache param error")
return
}
val, ok, err := p.cacheDriver.Get(param.Key)
if err != nil {
scope.Log(errors.Wrapf(err, "gcache plugin get key %s fail", param.Key))
return
}
if ok {
scope.Value = val
scope.SkipLeft()
}
}
func (p Plugin) afterQueryInvoke(scope *gorm.Scope) {
cacheOption, ok := scope.Get(CacheOption)
if !ok {
return
}
param, ok := cacheOption.(CacheParam)
if !ok {
scope.Log("cache param error")
return
}
if scope.HasError() {
return
}
reflectValue := scope.IndirectValue()
if reflectValue.IsNil() || reflectValue.Len() == 0 {
return
}
if err := p.cacheDriver.Set(param.Key, scope.Value, param.ttl); err != nil {
scope.Log(errors.Wrapf(err, "gcache plugin set key %s fail", param.Key))
return
}
}