WeezyEzoW
tRPC2y ago
19 replies
WeezyEzo

Ability to mutate/extend `input` from middlewares

Hi
I have a global middleware that should run for every route. This middleware simply coerces '' (empty string) to
undefined
for the whole
input
object.

Here is my setup:
export const defaultProcedure = t.procedure.use(async ({ next, getRawInput }) => {
  const input = await getRawInput()
  const newInput = coerceEmptyStringsToUndefined(input)
  return next({
    input: newInput,
  })
})


the function coerceEmptyStringsToUndefined is guarnteed to work as expected. Here is the implementation btw:
import mapValues from 'lodash.mapvalues'

// Note: not working with arrays
export function coerceEmptyStringsToUndefined(o: unknown): any {
  if (typeof o === 'object' && o !== null) {
    if (Array.isArray(o)) {
      // return something here if you want it to work with arrays
    } else {
      return mapValues(o, coerceEmptyStringsToUndefined)
    }
  }
  return o === '' ? undefined : o
}


The problem: this code throws a validation error
const testRouter = createTRPCRouter({
  test: defaultProcedure
    .input(
      z.object({
        a: z.number().optional(),
      })
    )
    .query(async ({ input }) => {
      console.log(input)
    }),
})


The error is from zod which is: {received: '""', expected: 'number'}.
Was this page helpful?