首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tRPC如何封装中间件?

tRPC如何封装中间件?
EN

Stack Overflow用户
提问于 2022-09-18 14:41:46
回答 2查看 270关注 0票数 1

我正在尝试将中间件应用到它自己的功能中,但我很难在它上找到合适的类型记录类型。

目前,我正在按以下方式键入中间件,但这并不理想,因为上下文和元数据的类型信息在从中间件返回后丢失。

在中间件内部

代码语言:javascript
复制
import { MiddlewareFunction } from "@trpc/server/dist/declarations/src/internals/middlewares";
import { TRPCError } from "@trpc/server";


export const authMiddleware : MiddlewareFunction<any, any, any> = async ({ ctx, next, path, rawInput, type, meta }) => {
  if (!meta?.auth)
    return next();

  // some random logic

  return next();
}

这就是我想要的消费方式

代码语言:javascript
复制
createRouter()
  .middleware(authMiddleware)
  .mutation('', {
    meta: {
      auth: "user",
      appCheck: true
    },
    input: object({
      workshopId: idSchema,
    }),
    resolve: async ({ input, ctx, type }) => {
    // Here ctx has been widened to any
    // ...

提前谢谢你。

EN

回答 2

Stack Overflow用户

发布于 2022-10-13 21:21:49

代码语言:javascript
复制
const t = initTRPC.context<Context>().create();
const middleware = t.middleware;

const authMiddleware = t.middleware(({ next, ctx }) => {
  if (!ctx.session) {
    throw new TRPCError({
      code: "UNAUTHORIZED",
    });
  }
  return next({
    ctx: {
      // Infers the `session` as non-nullable
      session: ctx.session,
    },
  });
})
票数 2
EN

Stack Overflow用户

发布于 2022-11-01 17:58:42

我也遇到了同样的问题(trpc v9.27),所以我直接从trpc路由器上的中间件方法获得了这个类型。

代码语言:javascript
复制
import * as trpc from "@trpc/server"

// context for router
const createContext = async () => ({hi: "hi"})

type Context = trpc.inferAsyncReturnType<typeof createContext>

// router initialization function
const trpcRouter = () => trpc.router<Context>()

const router = trpcRouter()
// don't forget to add the return type for your middleware
// in the generic
const init = router.middleware<Context>
type MiddlewareFunction = Parameters<typeof init>[0]

// now use for your middlewares
const myMiddleware: MiddlewareFunction = ({next, ctx}) => {
    console.log("my context", ctx)
    next()
}

// go nuts and use it where you want
export const myCoolRoutes = router
    .middleware(myMiddleware)
    .query("coolio", ({ctx}) => true)

请注意,如果您计划在您的一个中间件函数中更改上下文,那么router.middleware泛型应该反映这一点。例如,如果要在中间件中将键添加到上下文中,则需要定义一个新的上下文类型,该类型将添加所需的键:

代码语言:javascript
复制
// add your keys to context
type keys = {newKey: number}
const mutatingMiddleware = router.middleware<Context & keys>
type Mutate = Parameters<typeof mutatingMiddleware>[0]

const mutatator: Mutate = ({ctx, next}) => {
    return next({ctx: {...ctx, newKey: 0}})
}

希望这能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73763655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档