Files
trpc-nuxt/recipes/validation.md
2022-05-18 09:25:19 -07:00

924 B

Validation

tRPC works out-of-the-box with yup/superstruct/zod/myzod/custom validators. Learn more about input validation here.

Input Validation

// ~/server/trpc/index.ts
import { z } from 'zod'

export const router = trpc
  .router()
  .mutation('createUser', {
    // validate input with Zod
    input: z.object({
      name: z.string().min(5)
    }),
    async resolve(req) {
      // use your ORM of choice
      return await UserModel.create({
        data: req.input,
      })
    },
  })

Output Validation

// ~/server/trpc/index.ts
import { z } from 'zod'

export const router = trpc
  .router()
  .query('hello', {
    // validate output with Zod
    output: z.object({
      greeting: z.string()
    }),
    // expects return type of { greeting: string }
    resolve() {
      return {
        greeting: 'hello!',
      }
    },
  })