30 lines
778 B
TypeScript
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)
|
|
}
|