简体   繁体   中英

Nuxt 3 - after response middleware

I have a use-case where I would like to call a middleware after the response went through the route handler. The docs describe that the standard server middleware only runs BEFORE the request is handled ( https://nuxt.com/docs/guide/directory-structure/server ).

What I'd like to accomplish is:

// file: server/api/test/index.ts
export default defineEventHandler(async (event) => {
    return { "test": true }
})

When I call the endpoint via GET /api/test I would like the response to be:

{ "result": { "test": true } }

So basically mapping all APIs response in a object with key "result". This is quite easy to do with express middleware and other frameworks as you can usually await the route handler's result and then just wrap the result in the object.

How can this be accomplished with Nuxt 3 Middleware?

Middlewares purpose are for checking logic before the the endpoint gets executed. I don't think using a middleware will accomplish your task.

Here is one solution that does not involve any middleware:

you can create a custom function that maps your responses.

function mapResponse(data){
  return {
    result: data
  }
}

and use it inside you api endpoints like this:

export default defineEventHandler((event) => {
  return mapResponse({ "test": true })
})

then you can also customize the function however you want.

The awesome people over at the h3's GitHub page showed me a working solution.( https://github.com/unjs/h3/issues/397 )

// ~/server/utils/handler.ts
import type { H3Event } from 'h3'

export const defineMyHandler = (handler: (event: H3Event) => any) => {
  const _handler = async (event: H3Event) => {
    const response = await handler(event)

    const responseNew = doSome(response )

    return responseNew
  }

  return defineEventHandler(_handler)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM