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

Schema with default: null becomes default("null") in generated Zod code #188

Closed
robogeek opened this issue Dec 4, 2023 · 4 comments
Closed

Comments

@robogeek
Copy link

robogeek commented Dec 4, 2023

Bug description

An OpenAPI schema with default: null becomes default("null") in generated Zod code

For full information see: fabien0102/openapi-codegen#212

Input

  /**
   * Long name of program for human readability.
   *
   * @example Residential Time of Use-A
   * @default null
   */
  programLongName?: string | null;
  /**
   * Short name of energy retailer providing the program.
   *
   * @example ACME
   * @default null
   */
  retailerName?: string | null;

Expected output

programLongName: z.string().optional().nullable().default(null),
  retailerName: z.string().optional().nullable().default(null),

Actual output

programLongName: z.string().optional().nullable().default("null"),
  retailerName: z.string().optional().nullable().default("null"),

Versions

  • Typescript: v4.5.3
  • Zod: v3.22.4
@schiller-manuel
Copy link
Collaborator

null is currently not handled in the @default JSDoc parsing, see https://github.com/fabien0102/ts-to-zod/blob/main/src/core/jsDocTags.ts#L177

@tvillaren
Copy link
Collaborator

It would make sense to handle it, wouldn't it?

@schiller-manuel
Copy link
Collaborator

It would make sense to handle it, wouldn't it?

sure!
Ideally we would also validate the @default value, i.e. only accept null if the type is actually nullable.

@tvillaren
Copy link
Collaborator

Or set it to nullable if it detects null as a default.

This would be consistent with the already implemented behaviour of removing the question mark when a property has a default:

const removeOptionalTransformer: ts.TransformerFactory<ts.SourceFile> = (
context
) => {
const visit: ts.Visitor = (node) => {
node = ts.visitEachChild(node, visit, context);
if (ts.isPropertySignature(node)) {
const jsDocTags = getJSDocTags(node, sourceFile);
if (jsDocTags.default !== undefined) {
const type = node.type
? ts.visitEachChild(node.type, omitUndefinedKeyword, context)
: undefined;
return ts.factory.createPropertySignature(
node.modifiers,
node.name,
undefined, // Remove `questionToken`
type
);
}
}
return node;
};
return (node) => ts.visitNode(node, visit) as ts.SourceFile;
};

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

3 participants