0

I have the following input schema:

const inputSchema = z.union([
  z.object({
    id: z.string(),
  }),
  z.object({
    key: z.string(),
  }),
])

This schema works until I do:

import { generateOpenApiDocument } from 'trpc-openapi'

const openApiDocument = generateOpenApiDocument(trpcAppRouter, {
  title: 'title',
  baseUrl: '/route',
  version: '0.0.1',
})

When I generate pass the route with the input to generateOpenApiDocument then I get the error:

TRPCError: [query.thing.route] - Input parser must be a ZodObject

I guess it's a bug in generateOpenApiDocument that doesn't check the input correctly because it is a ZodObject but I'm not sure how to work around this.

HMR
  • 37,593
  • 24
  • 91
  • 160

2 Answers2

2

I found that trpc-opeapi uses zod-to-json-schema and zod-to-json-schema does not support union. Hence trpc-openapi does not support OpenAPI 3 spec.

HMR
  • 37,593
  • 24
  • 91
  • 160
1

Your thing route seems to be missing Zod validation.

The trpc-openapi library comes with certain requirements for the input and output validation for your route.

In the example below, the input is a string. But note that you can't use

input(z.string())

as validation, if you have a string argument it needs to wrapped by a Zod object:

input(z.object({ thing: z.string() }))

If there is no input, use z.void()

.input(z.void))

Note that you also need to specify the output from the route.

Example:

export const appRouter = t.router({
  thing: t.procedure
    .meta({ openapi: { method: 'GET', path: '/thing' } })
    .input(z.object({ thing: z.string() }))
    .output(z.object({ greeting: z.string() }))
    .query(({ input }) => {
      return { greeting: `Hello ${input.thing}!` };
    });
});

As is noted in the documentation, the following requirements need to be met for the procedure to support OpenAPI

  • Both input and output parsers are present AND use Zod validation.
  • Query input parsers extend Object<{ [string]: String | Number | BigInt | Date }> or Void.
  • Mutation input parsers extend Object<{ [string]: AnyType }> or Void.
  • meta.openapi.method is GET, POST, PATCH, PUT or DELETE.
  • meta.openapi.path is a string starting with /.
  • meta.openapi.path parameters exist in input parser as String | Number | BigInt | Date
ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
  • 1
    Thank you for your reply, I found that trpc-opeapi uses zod-to-json-schema and zod-to-json-schema does not support [union](https://swagger.io/specification/#discriminator-object). Hence trpc-openapi does not support [OpenAPI 3 spec](https://github.com/prosepilot/trpc-openapi/issues/255). – HMR Aug 22 '23 at 08:10
  • 1
    Thanks for the feedback @HMR! Good to know – ProgrammerPer Aug 24 '23 at 17:41