Files
zod-schema-class/src/schema/jsonified/date.ts
Julien Valverdé 9ddda594ef
Some checks failed
continuous-integration/drone/push Build is failing
Schema work
2024-03-19 18:25:56 +01:00

30 lines
778 B
TypeScript

import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
export type JsonifiedDate = Opaque<string, "@thilawyn/zod-schema-class/JsonifiedDate">
export function jsonifyDateSchema<S extends z.ZodType<Date>>(schema: S) {
return schema.transform(v => v.toString() as JsonifiedDate)
}
export function dejsonifyDateSchema<S extends z.ZodType<Date>>(schema: S) {
return z
.custom<JsonifiedDate>(identity)
.pipe(
z
.string()
.transform(v => {
try {
return new Date(v)
}
catch (e) {
return v
}
})
)
.pipe(schema)
}