The Hook feature allows us to bind CRUD hooks to the Model of the feature.

Relevant Definitions

Relevant Hook functions:

  1. type (
  2. HookFuncSelect func(ctx context.Context, in *HookSelectInput) (result Result, err error)
  3. HookFuncInsert func(ctx context.Context, in *HookInsertInput) (result sql.Result, err error)
  4. HookFuncUpdate func(ctx context.Context, in *HookUpdateInput) (result sql.Result, err error)
  5. HookFuncDelete func(ctx context.Context, in *HookDeleteInput) (result sql.Result, err error)
  6. )
  7. // HookHandler manages all supported hook functions for Model.
  8. type HookHandler struct {
  9. Select HookFuncSelect
  10. Insert HookFuncInsert
  11. Update HookFuncUpdate
  12. Delete HookFuncDelete
  13. }

Hook registration method:

  1. // Hook sets the hook functions for current model.
  2. func (m *Model) Hook(hook HookHandler) *Model

Usage Example

When querying the birth_day field, also calculate the current user’s age:

  1. // Hook function definition.
  2. var hook = gdb.HookHandler{
  3. Select: func(ctx context.Context, in *gdb.HookSelectInput) (result gdb.Result, err error) {
  4. result, err = in.Next(ctx)
  5. if err != nil {
  6. return
  7. }
  8. for i, record := range result {
  9. if !record["birth_day"].IsEmpty() {
  10. age := gtime.Now().Sub(record["birth_day"].GTime()).Hours() / 24 / 365
  11. record["age"] = gvar.New(age)
  12. }
  13. result[i] = record
  14. }
  15. return
  16. },
  17. }
  18. // It registers the hook function, creates and returns a new `model`.
  19. model := g.Model("user").Hook(hook)
  20. // The hook function takes effect on each ORM operation when using the `model`.
  21. all, err := model.Where("status", "online").OrderAsc(`id`).All()