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

How to indicate that a schema using a transform or preprocess can be nullable / optional? #143

Closed
codeinabox opened this issue May 23, 2023 · 3 comments · Fixed by #146
Closed

Comments

@codeinabox
Copy link

Is there a way to create a nullable transform with schema version 3.0.0? I had the following schema, which used coerce:

const aSchema = z.object({
  id: z.string(),
  date: z.coerce
    .string()
    .nullable()
    .openapi({ example: '2023-04-12', description: 'YYYY-MM-DD' }),
});

This correctly set nullable: true on the generated document. However due a bug with coerce colinhacks/zod#1760, I've had to switch to the following transform schema and I am having trouble getting it to say the field can be null in the response

const aSchema = z.object({
  id: z.string(),
  date: z
    .any()
    .transform((val: LocalDate | null) => (val ? String(val) : null))
    .nullable()
    .openapi({ example: '2023-04-12', description: 'YYYY-MM-DD', type: 'string' }),
});
@codeinabox
Copy link
Author

I've also tried this as a preprocess and have the same issue:

const aSchema = z.object({
  id: z.string(),
  date: z
    .preprocess(val => (val ? String(val) : null), z.string())
    .nullable()
    .openapi({ example: '2023-04-12', description: 'YYYY-MM-DD' }),
});

@codeinabox codeinabox changed the title How to indicate that a schema using a transform can be nullable? How to indicate that a schema using a transform or preprocess can be nullable / optional? May 23, 2023
@AGalabov
Copy link
Collaborator

@codeinabox thank you for using the library and helping us identify issues to make it better. I'll answer on issue in two ways:

  1. We've taken the decision that when a type property is passed then all of the documentation is the responsibility of the user - i.e leaving it up to him since he is modifying the main field. That is why the nullable is not being generated - you can add it manually.

  2. However for the coerce type this is no longer the issue. There is a problem on our side in this case. I'll open up a PR soon that should fix it.

AGalabov added a commit that referenced this issue May 31, 2023
AGalabov added a commit that referenced this issue May 31, 2023
…cess-and-any

Bugfix/#143 handle preprocess and any
@AGalabov
Copy link
Collaborator

@codeinabox some changes have been released with v5.1.0. With them the preprocess example should work.

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

Successfully merging a pull request may close this issue.

2 participants