doc: add transaction hooks to entgo.io (#600)

This commit is contained in:
Ariel Mashraki
2020-07-12 11:36:29 +03:00
committed by GitHub
parent e6c91e1dbf
commit 6cd1d18d46

View File

@@ -131,3 +131,39 @@ func Do(ctx context.Context, client *ent.Client) {
}
}
```
## Hooks
Same as [schema hooks](hooks.md#schema-hooks) and [runtime hooks](hooks.md#runtime-hooks), hooks can be registered on
active transactions, and will be executed on `Tx.Commit` or `Tx.Rollback`:
```go
func Do(ctx context.Context, client *ent.Client) error {
tx, err := client.Tx(ctx)
if err != nil {
return err
}
// Add a hook on Tx.Commit.
tx.OnCommit(func(next ent.Committer) ent.Committer {
return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// Code before the actual commit.
err := next.Commit(ctx, tx)
// Code after the transaction was committed.
return err
})
})
// Add a hook on Tx.Rollback.
tx.OnRollback(func(next ent.Rollbacker) ent.Rollbacker {
return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// Code before the actual rollback.
err := next.Rollback(ctx, tx)
// Code after the transaction was rolled back.
return err
})
})
//
// <Code goes here>
//
return err
}
```