Guide Writing Hooks - osama1998H/Moca GitHub Wiki

Writing Hooks

Register hooks in Initialize(cr, hr), priority ordering, dependency declarations, and document event constants.

Overview

Hooks let apps react to document events and register controller-aware behaviour during app initialization. In current Moca builds, hooks are registered from an app's Initialize(cr, hr) function, which is exposed through apps.MustRegisterInit(...) in hooks.go.

Document Event Hooks

package myapp

import (
    "github.com/osama1998H/moca/pkg/apps"
    "github.com/osama1998H/moca/pkg/document"
    "github.com/osama1998H/moca/pkg/hooks"
)

func init() {
    apps.MustRegisterInit("myapp", Initialize)
}

func Initialize(cr *document.ControllerRegistry, hr *hooks.HookRegistry) {
    _ = cr

    hr.Register("Sales Order", document.EventBeforeSave, hooks.PrioritizedHandler{
        AppName:  "myapp",
        Handler:  calculateTotal,
        Priority: 10,
    })

    hr.Register("Sales Order", document.EventAfterInsert, hooks.PrioritizedHandler{
        AppName:  "myapp",
        Handler:  sendNotification,
        Priority: 20,
    })
}

func calculateTotal(ctx *document.DocContext, doc document.Document) error {
    // Business logic here
    return nil
}

func sendNotification(ctx *document.DocContext, doc document.Document) error {
    return nil
}

Available Events

Use the document.Event... constants when registering handlers:

  • document.EventBeforeInsert
  • document.EventAfterInsert
  • document.EventBeforeValidate
  • document.EventValidate
  • document.EventBeforeSave
  • document.EventAfterSave
  • document.EventOnUpdate
  • document.EventBeforeSubmit
  • document.EventOnSubmit
  • document.EventBeforeCancel
  • document.EventOnCancel
  • document.EventOnTrash
  • document.EventAfterDelete
  • document.EventOnChange

Rename hooks are handled by document controllers rather than HookRegistry because they carry the old and new names.

Priority & Dependencies

  • Priority: Lower number runs first (10 before 20)
  • Dependencies: DependsOn lists app names that must run before yours
hr.Register("Sales Order", document.EventBeforeSave, hooks.PrioritizedHandler{
    AppName:   "pricing",
    Handler:   applyDiscount,
    Priority:  20,
    DependsOn: []string{"taxes"}, // Run after handlers registered by the taxes app
})

Related