You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can extend H3Context with eventHandler or onRequest option of createApp:
The following can extend H3EventContext by eventHandler:
// case: extend `H3EventContext ` for auth with `eventHandler`import{login}from'./my/app'exportdefaultdefineEventHandler(async(event)=>{constauth=awaitlogin(/* something options ... */)event.context.auth=auth}
However, since this extends the H3EventContext per request, there are cases such as store or i18n where a one-time initialization is required, and we may want to extend it at app instance creation time with createApp, rather than per request.
The following is an example of initializing an i18n resource (context) in the form of a hook called only once on an app instance called onContext in the options of createApp.
import{createApp,H3EventContext,eventHandler}from'h3'import{CoreContext,createCoreContext,translate}from'@intlify/core'// we can import locale messages dynamicallyimportenfrom'./locales/en.json'declare module 'h3'{interfaceH3EventContext{i18n: CoreContext}}// setup i18n instance via `onContext` of `createApp`constapp=createApp({onContext(context: H3EventContext){consti18n=createCoreContext({locale: 'en',messages: {
en,},// some i18n options here ...})// set i18n instance to contextcontext.i18n=i18n},})app.use('/',eventHandler((event)=>{constmessage=translate(event.context.i18n,'hello',{name: 'h3'})returnmessage}),)
For H3EventContext type definition extending, we need to think about #496 and #511
Additional information
Would you be willing to help implement this feature?
The text was updated successfully, but these errors were encountered:
kazupon
changed the title
Extending H3EventContext with createApp
Extending H3EventContext with createAppOct 13, 2023
Describe the feature
We can extend
H3Context
witheventHandler
oronRequest
option ofcreateApp
:The following can extend
H3EventContext
byeventHandler
:However, since this extends the
H3EventContext
per request, there are cases such as store or i18n where a one-time initialization is required, and we may want to extend it at app instance creation time withcreateApp
, rather than per request.The following is an example of initializing an i18n resource (context) in the form of a hook called only once on an app instance called
onContext
in the options ofcreateApp
.For
H3EventContext
type definition extending, we need to think about #496 and #511Additional information
The text was updated successfully, but these errors were encountered: