-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
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
Document the use of async functions in hooks. #1593
Comments
Wouldn't the following paragraph in Hooks.md address this issue?
|
Would you like to send a PR? |
Sorry for not being clearer: what I mean is that paragraph is already in the docs. |
He is referring to Routes.md |
That is not sufficient as quite a few people have asked/made this mistake recently between gitter and help. |
Wild idea: check at startup if is an async function and the arity, and if it is an async function with 3 arguments, throw an error. |
FYI: I make this mistake myself routinely. |
I am experiencing this right now. What is the suggested way to implement multiple preHandlers, or any lifecycle hook, asynchronously? |
Can you paste some code that is not working for you? Have you tried using an array? |
This is essentially what my endpoint looks like. This could very well be an anti-pattern as I am new to how the handlers work in fastify. I am open to any suggestions on a proper way of handling this. |
You can call addHook twice, it should all work fine. |
Okay cool. I would ideally like to clean up the route though and extract that addHook logic. What is the suggested method on extracting that code so I could still stay in scope? |
Just pass an option object with a “preHandler” property with an array and your two functions. Let me know if it works! |
Awesome, it's working as expected and much more elegant than having the addHook block directly in the handler. Appreciate all the help! |
This doc needs to be improved ;). |
Closing thanks to improved docs by @RafaelGSS 💪 |
What about error managing in an async hook? The hooks docs specify to use https://www.fastify.io/docs/latest/Hooks/#manage-errors-from-a-hook |
you need to |
Sure why not! Edit: |
🐛 Bug Report
The current documentation is incorrect on how hooks works, as we state:
We need to document that
async preValidation(request, reply)
is also correct, butasync preValidation(request, reply, done)
is not.The text was updated successfully, but these errors were encountered: