Skip to content

Commit

Permalink
FIX: handle negative minimum, maximum, and default values from jsDoc
Browse files Browse the repository at this point in the history
Closes #227
  • Loading branch information
mrdan committed Jul 11, 2024
1 parent 1e41364 commit 1160c0a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
15 changes: 14 additions & 1 deletion src/core/generateZodSchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,13 @@ describe("generateZodSchema", () => {
* @maxLength 123
*/
blockedPhoneNumbers: string[];
/**
* The angle of the hero's raised or furrowed eyebrow.
*
* @minimum -45 @maximum -5 @default -20
*/
eyebrowAngle: number;
}`;
expect(generate(source)).toMatchInlineSnapshot(`
"export const heroContactSchema = z.object({
Expand Down Expand Up @@ -858,7 +865,13 @@ describe("generateZodSchema", () => {
* @minLength 56
* @maxLength 123
*/
blockedPhoneNumbers: z.array(z.string().regex(/^([+]?d{1,2}[-s]?|)d{3}[-s]?d{3}[-s]?d{4}$/)).min(56).max(123)
blockedPhoneNumbers: z.array(z.string().regex(/^([+]?d{1,2}[-s]?|)d{3}[-s]?d{3}[-s]?d{4}$/)).min(56).max(123),
/**
* The angle of the hero's raised or furrowed eyebrow.
*
* @minimum -45 @maximum -5 @default -20
*/
eyebrowAngle: z.number().min(-45).max(-5).default(-20)
});"
`);
});
Expand Down
23 changes: 20 additions & 3 deletions src/core/jsDocTags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,12 @@ export function jsDocTagToZodProperties(
zodProperties.push({
identifier: "min",
expressions: withErrorMessage(
f.createNumericLiteral(jsDocTags.minimum.value),
jsDocTags.minimum.value < 0
? f.createPrefixUnaryExpression(
ts.SyntaxKind.MinusToken,
f.createNumericLiteral(Math.abs(jsDocTags.minimum.value))
)
: f.createNumericLiteral(jsDocTags.minimum.value),
jsDocTags.minimum.errorMessage
),
});
Expand All @@ -259,7 +264,12 @@ export function jsDocTagToZodProperties(
zodProperties.push({
identifier: "max",
expressions: withErrorMessage(
f.createNumericLiteral(jsDocTags.maximum.value),
jsDocTags.maximum.value < 0
? f.createPrefixUnaryExpression(
ts.SyntaxKind.MinusToken,
f.createNumericLiteral(Math.abs(jsDocTags.maximum.value))
)
: f.createNumericLiteral(jsDocTags.maximum.value),
jsDocTags.maximum.errorMessage
),
});
Expand Down Expand Up @@ -338,7 +348,14 @@ export function jsDocTagToZodProperties(
: jsDocTags.default === false
? [f.createFalse()]
: typeof jsDocTags.default === "number"
? [f.createNumericLiteral(jsDocTags.default)]
? jsDocTags.default < 0
? [
f.createPrefixUnaryExpression(
ts.SyntaxKind.MinusToken,
f.createNumericLiteral(Math.abs(jsDocTags.default))
),
]
: [f.createNumericLiteral(jsDocTags.default)]
: jsDocTags.default === null
? [f.createNull()]
: [f.createStringLiteral(jsDocTags.default)],
Expand Down

0 comments on commit 1160c0a

Please sign in to comment.