简体   繁体   English

Nuxt 3 - 后响应中间件

[英]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 ).文档描述标准服务器中间件仅在处理请求之前运行( 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:当我通过 GET /api/test 调用端点时,我希望响应是:

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

So basically mapping all APIs response in a object with key "result".所以基本上将所有 API 响应映射到 object 中,键为“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.使用 express 中间件和其他框架很容易做到这一点,因为您通常可以等待路由处理程序的结果,然后将结果包装在 object 中。

How can this be accomplished with Nuxt 3 Middleware?这如何通过 Nuxt 3 中间件来完成?

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 来映射您的响应。

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

and use it inside you api endpoints like this:并在你内部使用它 api 端点,如下所示:

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

then you can also customize the function however you want.然后您还可以根据需要自定义 function。

The awesome people over at the h3's GitHub page showed me a working solution.( https://github.com/unjs/h3/issues/397 ) h3 的 GitHub 页面上很棒的人向我展示了一个可行的解决方案。( 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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