Skip to content

Commit

Permalink
chore: fix number and bigint coercion
Browse files Browse the repository at this point in the history
  • Loading branch information
lifeiscontent committed Aug 9, 2024
1 parent 6b98c07 commit 790c192
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/hip-actors-wink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@conform-to/zod': minor
---

fix number and bigint coercion
18 changes: 13 additions & 5 deletions packages/conform-zod/coercion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
schema = any()
.transform((value) =>
coerceString(value, (text) =>
text.trim() === '' ? Number.NaN : Number(text),
text.trim() === '' ? text : Number(text),
),
)
.pipe(type);
Expand All @@ -132,14 +132,14 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
} else if (def.typeName === 'ZodDate') {
schema = any()
.transform((value) =>
coerceString(value, (timestamp) => {
const date = new Date(timestamp);
coerceString(value, (text) => {
const date = new Date(text);

// z.date() does not expose a quick way to set invalid_date error
// This gets around it by returning the original string if it's invalid
// See https://github.com/colinhacks/zod/issues/1526
if (isNaN(date.getTime())) {
return timestamp;
return text;
}

return date;
Expand All @@ -148,7 +148,15 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
.pipe(type);
} else if (def.typeName === 'ZodBigInt') {
schema = any()
.transform((value) => coerceString(value, BigInt))
.transform((value) =>
coerceString(value, (text) => {
try {
return BigInt(text);
} catch {
return text;
}
}),
)
.pipe(type);
} else if (def.typeName === 'ZodArray') {
schema = any()
Expand Down

0 comments on commit 790c192

Please sign in to comment.