Closed cyrilchapon closed 5 months ago
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Had the same problem and found a "simpler" solution https://github.com/colinhacks/zod/discussions/879#discussioncomment-7292834 :
const stringToValidDate = z.coerce.date().transform((dateString, ctx) => {
const date = new Date(dateString)
if (!z.date().safeParse(date).success) {
ctx.addIssue({
code: z.ZodIssueCode.invalid_date,
})
}
return date
})
const stuffDTO = z.object({
someName: z.string(),
someDate: stringToValidDate, // it is a Date
})
Working with dates is inherently a little complex when typing an API.
There are currently 2 use-cases that I would like to see covered in such a library like Zodios :
What I naïvely tried first :
api-def.ts
handler.ts
component.tsx
I was naively thinking that both
in server
and in client
would do the trick, but apparently not.
So I thought "hey, actually I have to tell Zodios how to serialize and parse the date". And gave a shot :
But the trick is now (with transforms) both the server-side and the client side expects a string So I went :
in server
and in client
But I had to disable transformation for request in the client
This is now sort of "working", but I don't find it elegant.
I extensively searched "Zodios date" accross repos issues and discussions without any success; and I'm pretty surprised I'm the first to encounter this. Am I missing something ?
As a side note; the recommended way to parse dates string in zod is the following.
Which accepts a string in input, validate its appearance as an ISO8601 datetime, then coerces it into a
Date
object. Perfect.