fix(hooks): enabled use of useAppConfig() and useRuntimeConfig() within request hooks
If the nitro context isn't already initialized, it will be initialized, rather than error.
๐ Linked issue
โ Type of change
- [ ] ๐ Documentation (updates to the documentation, readme, or JSdoc annotations)
- [x] ๐ Bug fix (a non-breaking change that fixes an issue)
- [ ] ๐ Enhancement (improving an existing functionality like performance)
- [ ] โจ New feature (a non-breaking change that adds functionality)
- [ ] ๐งน Chore (updates to the build process or auxiliary tools and libraries)
- [ ] โ ๏ธ Breaking change (fix or feature that would cause existing functionality to change)
๐ Description
When calling useAppConfig(event) or useRuntimeConfig(event) from within a hook, the hook errors, because the "nitro" context option is not initialized yet at that time. It does get initialized later, making it available in middleware and route handlers. This PR extends support to include hooks as well, since although the nitro context option is not initialized, the event is available, so one would expect it to work.
๐ Checklist
- [ ] I have linked an issue or discussion.
- [x] I have updated the documentation accordingly.
Thanks for PR. Can you please link to a minimal reproduction please? ๐๐ผ
Thanks for PR. Can you please link to a minimal reproduction please? ๐๐ผ
What about the changes in the tests?
Specifically, test/fixture/plugins/hooks.ts and test/fixture/routes/hooks.ts.
That's pretty much as minimal of a reproduction as you can get.
Restore src/runtime/config.ts to its current state (as opposed to the state in this PR), while keeping the tests files as in this PR, and you will see the tests fail. Surrounding the hook handler with try {} catch (e) { console.error(e);} will show you a message like TypeError: Cannot read properties of undefined (reading 'runtimeConfig') (although exact message may depend on env; this example is from local nodejs installation). The output is wrong regardless, which is why I didn't add it into the test.
I have this fairly minimal project of mine: https://github.com/boenrobot/nuxt-mikro-orm-module
Where I originally encountered this issue, but even that one is not quite as minimal as the test case changes.