github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/couchdb/hooks.go (about)

     1  package couchdb
     2  
     3  import (
     4  	"github.com/cozy/cozy-stack/pkg/prefixer"
     5  	"github.com/cozy/cozy-stack/pkg/realtime"
     6  )
     7  
     8  // Hook is a function called before a change is made into
     9  // A hook can block the event by returning an error
    10  type listener func(db prefixer.Prefixer, doc Doc, old Doc) error
    11  
    12  type key struct {
    13  	DocType string
    14  	Event   string
    15  }
    16  
    17  var hooks map[key][]listener
    18  
    19  // Events to hook into
    20  const (
    21  	EventCreate = realtime.EventCreate
    22  	EventUpdate = realtime.EventUpdate
    23  	EventDelete = realtime.EventDelete
    24  )
    25  
    26  // Run runs all hooks for the given event.
    27  func runHooks(db prefixer.Prefixer, event string, doc Doc, old Doc) error {
    28  	if hs, ok := hooks[key{doc.DocType(), event}]; ok {
    29  		for _, h := range hs {
    30  			err := h(db, doc, old)
    31  			if err != nil {
    32  				return err
    33  			}
    34  		}
    35  	}
    36  	return nil
    37  }
    38  
    39  // AddHook adds an hook for the given doctype and event.
    40  // Useful for special doctypes cleanup
    41  func AddHook(doctype, event string, hook listener) {
    42  	if hooks == nil {
    43  		hooks = make(map[key][]listener)
    44  	}
    45  	k := key{doctype, event}
    46  	hs, ok := hooks[k]
    47  	if !ok {
    48  		hs = make([]listener, 0)
    49  	}
    50  	hooks[k] = append(hs, hook)
    51  }