fastify / fastify-swagger

Swagger documentation generator for Fastify
MIT License
889 stars 199 forks source link

Zod schema references ($ref) breaking fastify route querystrings #799

Open wuahi opened 2 months ago

wuahi commented 2 months ago

Prerequisites

Fastify version

4.26.1

Plugin version

No response

Node.js version

20.11.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04.4

Description

When using zod buildJsonSchemas to build the schema references, the querystring parameter in route schema breaks down.

// schema.ts

import { buildJsonSchemas } from 'fastify-zod'

...
const getPermissionsInputSchema = z.object({ users: z.array(z.string()) })

const { schemas: permissionSchemas, $ref } = buildJsonSchemas(
    {
        getPermissionsResponseSchema,
        getPermissionsInputSchema,
        getPermissionResponseSchema,
        updatePermissionsInputSchema,
        updatePermissionsResponseSchema,
        updatePermissionClaimsInputSchema,
        updatePermissionClaimsResponseSchema,
    },
    {
        $id: 'permissionSchemas',
    },
)

// route.ts

interface GetPermissionsInterface extends RouteGenericInterface {
    Querystring: GetPermissionsInput
}

server.get<GetPermissionsInterface>(
        '/permissions',
        {
            onRequest: [server.authenticate],
            schema: {
                tags: ['permissions'],
                description: 'For getting aggregate permissions of a collection of users',
                querystring: $ref('getPermissionsInputSchema'),
                response: { '2xx': $ref('getPermissionsResponseSchema') },
            },
        },
        getPermissionsHandler,
)

Swagger looks like it is trying to include every schema in the permission schemas collection, instead of the required getpermissionsInputSchema: image

Link to code that reproduces the bug

No response

Expected Behavior

I would expect this to show the query parameters as it shows them for the "body" or "response" segment. I am quite confused why it's not doing so.

I found other bugs that seemed somewhat related to this, but none of them seemed to have resolved properly.

mcollina commented 2 months ago

Thanks for reporting!

Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.