y_nkY
tRPC4mo ago
24 replies
y_nk

creating middleware with context type as param

i'm looking into build a "post operation" function into separate piece of code. i know it may be done differently but i'm looking into it for code structure purpose. the goal of the middleware is to accept a function which takes the current context as input, as well as the result from the handler, and execute code.

import type { MiddlewareResult } from '@trpc/server'
import { initTRPC } from '@trpc/server'

import type { Context } from '../context'

type Action<C, R> = (opts: {
  ctx: C
  result: MiddlewareResult<R>
}) => unknown | Promise<unknown>

export function post<C, R>(action: Action<C, R>) {
  const t = initTRPC.context<Pick<Context, 'get'>>().create()

  return t.procedure
    .use(async ({ ctx, next }) => {
      const result = await next()

      action({ ctx, result })

      return result
    })
}


my problems are:
1. i have no idea how to get the C (context) type right
2. the MiddlewareResult<> type is not exposed from @trpc/server so i can't pull it.

my questions are:
1. can it be done?
2. how difficult it should be?
3. somebody has pointer on it? help please

thanks
Was this page helpful?