-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.go
127 lines (102 loc) · 2.44 KB
/
hooks.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package mgm
import "go.mongodb.org/mongo-driver/mongo"
// CreatingHook is called before saving a new model to the database
type CreatingHook interface {
Creating() error
}
// CreatedHook is called after a model has been created
type CreatedHook interface {
Created() error
}
// UpdatingHook is called before updating a model
type UpdatingHook interface {
Updating() error
}
// UpdatedHook is called after a model is updated
type UpdatedHook interface {
Updated(result *mongo.UpdateResult) error
}
// SavingHook is called before a model (new or existing) is saved to the database.
type SavingHook interface {
Saving() error
}
// SavedHook is called after a model is saved to the database.
type SavedHook interface {
Saved() error
}
// DeletingHook is called before a model is deleted
type DeletingHook interface {
Deleting() error
}
// DeletedHook is called after a model is deleted
type DeletedHook interface {
Deleted(result *mongo.DeleteResult) error
}
func callToBeforeCreateHooks(model Model) error {
if hook, ok := model.(CreatingHook); ok {
if err := hook.Creating(); err != nil {
return err
}
}
if hook, ok := model.(SavingHook); ok {
if err := hook.Saving(); err != nil {
return err
}
}
return nil
}
func callToBeforeUpdateHooks(model Model) error {
if hook, ok := model.(UpdatingHook); ok {
if err := hook.Updating(); err != nil {
return err
}
}
if hook, ok := model.(SavingHook); ok {
if err := hook.Saving(); err != nil {
return err
}
}
return nil
}
func callToAfterCreateHooks(model Model) error {
if hook, ok := model.(CreatedHook); ok {
if err := hook.Created(); err != nil {
return err
}
}
if hook, ok := model.(SavedHook); ok {
if err := hook.Saved(); err != nil {
return err
}
}
return nil
}
func callToAfterUpdateHooks(updateResult *mongo.UpdateResult, model Model) error {
if hook, ok := model.(UpdatedHook); ok {
if err := hook.Updated(updateResult); err != nil {
return err
}
}
if hook, ok := model.(SavedHook); ok {
if err := hook.Saved(); err != nil {
return err
}
}
return nil
}
func callToBeforeDeleteHooks(model Model) error {
if hook, ok := model.(DeletingHook); ok {
if err := hook.Deleting(); err != nil {
return err
}
}
return nil
}
func callToAfterDeleteHooks(deleteResult *mongo.DeleteResult, model Model) error {
if hook, ok := model.(DeletedHook); ok {
if err := hook.Deleted(deleteResult); err != nil {
return err
}
}
return nil
}