feat: Allow configuring global hooks via Kong's functional options (#511)
Lets you pass `kong.WithBeforeApply` along with a function that supports dynamic bindings to register a `BeforeApply` hook without tying it directly to a node in the schema. Co-authored-by: Sutina Wipawiwat <swipawiwat@squareup.com>
This commit is contained in:
@@ -308,10 +308,16 @@ func main() {
|
||||
|
||||
## Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()
|
||||
|
||||
If a node in the CLI, or any of its embedded fields, has a `BeforeReset(...) error`, `BeforeResolve
|
||||
(...) error`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those
|
||||
methods will be called before values are reset, before validation/assignment,
|
||||
and after validation/assignment, respectively.
|
||||
If a node in the CLI, or any of its embedded fields, implements a `BeforeReset(...) error`, `BeforeResolve
|
||||
(...) error`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those will be called as Kong
|
||||
resets, resolves, validates, and assigns values to the node.
|
||||
|
||||
| Hook | Description |
|
||||
| --------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| `BeforeReset` | Invoked before values are reset to their defaults (as defined by the grammar) or to zero values |
|
||||
| `BeforeResolve` | Invoked before resolvers are applied to a node |
|
||||
| `BeforeApply` | Invoked before the traced command line arguments are applied to the grammar |
|
||||
| `AfterApply` | Invoked after command line arguments are applied to the grammar **and validated**` |
|
||||
|
||||
The `--help` flag is implemented with a `BeforeReset` hook.
|
||||
|
||||
@@ -340,6 +346,10 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
It's also possible to register these hooks with the functional options
|
||||
`kong.WithBeforeReset`, `kong.WithBeforeResolve`, `kong.WithBeforeApply`, and
|
||||
`kong.WithAfterApply`.
|
||||
|
||||
## The Bind() option
|
||||
|
||||
Arguments to hooks are provided via the `Run(...)` method or `Bind(...)` option. `*Kong`, `*Context`, `*Path` and parent commands are also bound and finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`.
|
||||
|
||||
Reference in New Issue
Block a user