New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add hooks for life cycle events: using .preAction(), .postAction() #1519
Conversation
This is a rework of the signature for life cycle events from #1514:
This gives a cleaner callback, especially when caller only cares about So looks like: program
.preAction((thisCommand, actionCommand) => {});
.postAction((thisCommand, actionCommand) => {}); instead of program
.hook('beforeAction', (context) => {});
.hook('afterAction', (context) => {}); |
For an example of the alternative approach of a single hook routine which is passed an event name rather than separately named methods for the hooks, see: https://www.fastify.io/docs/latest/Hooks/ A key reason for the single hook approach is if there are going to be lots of hooks. The pattern is similar to eventEmitter and |
For interest, also noticed in the fastify docs:
Commander does the same with the |
I am quite liking how Thinking of switching back to hook! This time with parameters: program
.hook('preAction', (thisCommand, actionCommand) => {});
.hook('postAction', (thisCommand, actionCommand) => {}); |
Pull Request
Problem
People ask for a way to run code before the action handler with access to the parsed options. And also some requests for a hook after the action.
Main issue: #1197
Related issues: #76 #229 #936 #996 #1158 #1457
Solution
Add
.preAction()
and.postAction()
methods:Triggered by action handler for hooked command and its subcommands.
Callback passed two Command parameters:
thisCommand
: the command which the hook is added to, useful for working with global properties.actionCommand
: the command with the action handlerChangeLog
.preAction()
and.postAction()
hooks