Files
zod-schema-class/src/schema/jsonifiable/date.ts
Julien Valverdé abac0f3747
All checks were successful
continuous-integration/drone/push Build is passing
jsonify -> jsonifiable
2024-03-09 21:38:37 +01:00

29 lines
720 B
TypeScript

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