Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

z.coerce.date() rendered as nullable #286

Open
tmokmss opened this issue Dec 22, 2024 · 0 comments
Open

z.coerce.date() rendered as nullable #286

tmokmss opened this issue Dec 22, 2024 · 0 comments

Comments

@tmokmss
Copy link

tmokmss commented Dec 22, 2024

Hi, I have a question about the conversion behavior of z.coerce.date.

With the below code:

import { OpenApiGeneratorV31, extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi";
import { z } from 'zod';
extendZodWithOpenApi(z);

const UserSchema = z
  .object({
    createdAt: z.coerce.date(),
  })
  .openapi('User');

const generator = new OpenApiGeneratorV31([UserSchema]);
const schema = generator.generateComponents();
console.log(JSON.stringify(schema, undefined, 2));

we get the following output:

{
  "components": {
    "schemas": {
      "User": {
        "type": "object",
        "properties": {
          "createdAt": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "required": [
          "createdAt"
        ]
      }
    },
    "parameters": {}
  }
}

The problem for me is that createdAt is rendered as nullable, where I want it to render as just string. Is there any workaround? I guess it contains null because z.coerce.date().parse(null) is valid, but not sure if it makes sense when it comes to openapi response schema.

Context: I use zod-prisma-types to generate zod schema from prisma schema, and it generates z.coerce.string() from a DateTime column as below:

// schema.prisma
model User {
  createdAt DateTime
}

// the generated zod type
export const User = z.object({
  createdAt: z.coerce.date(),
})

And when I want to directly use the schema as response type, the createdAt field unexpectedly becomes nullable.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant