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 2, 2024
1 parent 6b98c07 commit f2aed72
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 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
28 changes: 21 additions & 7 deletions packages/conform-zod/coercion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,15 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
} else if (def.typeName === 'ZodNumber') {
schema = any()
.transform((value) =>
coerceString(value, (text) =>
text.trim() === '' ? Number.NaN : Number(text),
),
coerceString(value, (text) => {
const number = Number(text);

if (isNaN(number)) {
return text;
}

return number;
}),
)
.pipe(type);
} else if (def.typeName === 'ZodBoolean') {
Expand All @@ -132,14 +138,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 +154,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
2 changes: 1 addition & 1 deletion tests/conform-zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ describe('conform-zod', () => {
).toEqual({
status: 'error',
payload: { test: ' ' },
error: { test: ['invalid'] },
error: { test: ['min'] },
reply: expect.any(Function),
});
});
Expand Down

0 comments on commit f2aed72

Please sign in to comment.