elierotenberg / fastify-zod

Zod integration with Fastify
MIT License
212 stars 19 forks source link

Support for nullable field #50

Closed sergey-pogranichnyi closed 1 month ago

sergey-pogranichnyi commented 1 month ago

.nullable() zod property doesn't work correctly.

Reproducible case:

// Define custom messages
import { z } from 'zod';
import fastify from 'fastify';
import { buildJsonSchemas, FastifyZod, register } from 'fastify-zod';

const TodoItemId = z.object({
  id: z.string().or(z.null()),
});

const models = {
  TodoItemId,
};

declare module 'fastify' {
  interface FastifyInstance {
    readonly zod: FastifyZod<typeof models>;
  }
}

(async () => {
  // Then configure fastify
  const f = fastify(
  });

  await register(f, {
    jsonSchemas: buildJsonSchemas(models),
    swaggerOptions: {
      openapi: {
        info: {
          title: '1',
          description: '2',
          version: '2.0.0',
        },
      },
    },
    swaggerUiOptions: {
      routePrefix: '/doc',
      staticCSP: true,
    },
  });

  f.zod.get(
    '/todo',
    {
      operationId: '',
      response: {
        200: 'TodoItemId',
      },
    },
    async () => {
      return {
        id: '1',
      };
    },
  );
  await f.listen({
    port: 3000,
  });
})();

Which produces incorrect type for the schema:

image
Zapotinschii-Augustin commented 1 month ago

Try to use openapi v3.1, i believe by default is openapi v3, and prabably v3 don't support nullable image

sergey-pogranichnyi commented 1 month ago

Try to use openapi v3.1, i believe by default is openapi v3, and prabably v3 don't support nullable image

Thanks, it helped:

  await register(f, {
    jsonSchemas: buildJsonSchemas(models),
    swaggerOptions: {
      openapi: {
        openapi: '3.1.0',
        info: {
          title: '1',
          description: '2',
          version: '2.0.0',
        },
      },
    },
    swaggerUiOptions: {
      routePrefix: '/doc',
      staticCSP: true,
    },
  });