-
Notifications
You must be signed in to change notification settings - Fork 137
/
hooks.go
51 lines (44 loc) · 1.1 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
package couchdb
import (
"github.com/cozy/cozy-stack/pkg/prefixer"
"github.com/cozy/cozy-stack/pkg/realtime"
)
// Hook is a function called before a change is made into
// A hook can block the event by returning an error
type listener func(db prefixer.Prefixer, doc Doc, old Doc) error
type key struct {
DocType string
Event string
}
var hooks map[key][]listener
// Events to hook into
const (
EventCreate = realtime.EventCreate
EventUpdate = realtime.EventUpdate
EventDelete = realtime.EventDelete
)
// Run runs all hooks for the given event.
func runHooks(db prefixer.Prefixer, event string, doc Doc, old Doc) error {
if hs, ok := hooks[key{doc.DocType(), event}]; ok {
for _, h := range hs {
err := h(db, doc, old)
if err != nil {
return err
}
}
}
return nil
}
// AddHook adds an hook for the given doctype and event.
// Useful for special doctypes cleanup
func AddHook(doctype, event string, hook listener) {
if hooks == nil {
hooks = make(map[key][]listener)
}
k := key{doctype, event}
hs, ok := hooks[k]
if !ok {
hs = make([]listener, 0)
}
hooks[k] = append(hs, hook)
}