gorm/callback.go

88 lines
1.9 KiB
Go
Raw Normal View History

2014-01-23 12:43:39 +04:00
package gorm
type callback struct {
2014-01-24 17:52:26 +04:00
create []func()
update []func()
delete []func()
query []func()
processors []*callback_processor
}
type callback_processor struct {
name string
before string
after string
replace bool
typ string
processor func()
callback *callback
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
func (c *callback) addProcessor(typ string) *callback_processor {
cp := &callback_processor{typ: typ, callback: c}
c.processors = append(c.processors, cp)
return cp
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
func (c *callback) Create() *callback_processor {
return c.addProcessor("create")
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
func (c *callback) Update() *callback_processor {
return c.addProcessor("update")
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
func (c *callback) Delete() *callback_processor {
return c.addProcessor("delete")
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
func (c *callback) Query() *callback_processor {
return c.addProcessor("query")
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
func (c *callback) Sort() {
creates, updates, deletes, queries := []*callback_processor{}, []*callback_processor{}, []*callback_processor{}, []*callback_processor{}
2014-01-23 12:43:39 +04:00
2014-01-24 17:52:26 +04:00
for _, processor := range c.processors {
switch processor.typ {
case "create":
creates = append(creates, processor)
case "update":
updates = append(updates, processor)
case "delete":
deletes = append(deletes, processor)
case "query":
queries = append(queries, processor)
2014-01-23 12:43:39 +04:00
}
}
}
2014-01-24 17:52:26 +04:00
func (cp *callback_processor) Before(name string) *callback_processor {
cp.before = name
return cp
}
func (cp *callback_processor) After(name string) *callback_processor {
cp.after = name
return cp
}
func (cp *callback_processor) Register(name string, fc func()) {
cp.name = name
cp.processor = fc
cp.callback.Sort()
}
func (cp *callback_processor) Remove(name string) {
cp.Replace(name, func() {})
}
2014-01-23 12:43:39 +04:00
2014-01-24 17:52:26 +04:00
func (cp *callback_processor) Replace(name string, fc func()) {
cp.name = name
cp.processor = fc
cp.replace = true
cp.callback.Sort()
2014-01-23 12:43:39 +04:00
}
2014-01-24 17:52:26 +04:00
var DefaultCallback = &callback{processors: []*callback_processor{}}