我正在尝试将中间件应用到它自己的功能中,但我很难在它上找到合适的类型记录类型。
目前,我正在按以下方式键入中间件,但这并不理想,因为上下文和元数据的类型信息在从中间件返回后丢失。
在中间件内部
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();
}这就是我想要的消费方式
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
// ...提前谢谢你。
发布于 2022-10-13 21:21:49
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,
},
});
})发布于 2022-11-01 17:58:42
我也遇到了同样的问题(trpc v9.27),所以我直接从trpc路由器上的中间件方法获得了这个类型。
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泛型应该反映这一点。例如,如果要在中间件中将键添加到上下文中,则需要定义一个新的上下文类型,该类型将添加所需的键:
// 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}})
}希望这能有所帮助。
https://stackoverflow.com/questions/73763655
复制相似问题