unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability
https://h3.unjs.io/
MIT License
3.53k stars 206 forks source link

trying to use defineEventHandler with before[] for per-route middleware #862

Open acidjazz opened 1 month ago

acidjazz commented 1 month ago

Environment

I noticed that in this merge https://github.com/unjs/h3/pull/485 there is before: [] - i tried something like this:

const index = defineEventHandler({
  handler: async () => {
    return metapi().render(
      await prisma.user.findMany({
      }),
    )
  },
  before: [
    () => {
      console.log('we are in before[]')
      return auth.user() && auth.user().isAdmin
    },
  ],
})

Reproduction

Just run the above code in a route

Describe the bug

not sure if i'm using before: [] incorrectly?

Additional context

No response

Logs

No response

offizium-berndstorath commented 1 month ago

Read https://h3.unjs.io/guide/event-handler#object-syntax

acidjazz commented 1 month ago

Read https://h3.unjs.io/guide/event-handler#object-syntax

Are you saying I should use onRequest: [] instead of before: [] ?

alifnuryana commented 5 days ago

Read https://h3.unjs.io/guide/event-handler#object-syntax

I think the documentation for defineEventHandler is incomplete.

there is no example of how to apply defineEventHandler with object syntax.

what if i want to create middleware at a non-global route level. did i make defineEventHandler in another file that accepts the object event then I called it on the body defineEventHandler by inserting an event object in the route level?