Last active
May 2, 2024 14:00
-
-
Save alexturpin/505a749a5e97792ea9d23ea50e02ab44 to your computer and use it in GitHub Desktop.
Temporal with Zod + tRPC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Temporal } from "@js-temporal/polyfill" | |
import { z } from "zod" | |
/* | |
"Zod extras", use like z. | |
date: zx.instant() | |
*/ | |
export const zx = { | |
instant: () => | |
z | |
.instanceof(Temporal.Instant) | |
.refine((v) => attempt(() => Temporal.Instant.from(v))) | |
.transform((v) => Temporal.Instant.from(v)), | |
zonedDateTime: () => | |
z | |
.instanceof(Temporal.ZonedDateTime) | |
.refine((v) => attempt(() => Temporal.ZonedDateTime.from(v))) | |
.transform((v) => Temporal.ZonedDateTime.from(v)), | |
plainDate: () => | |
z | |
.instanceof(Temporal.PlainDate) | |
.refine((v) => attempt(() => Temporal.PlainDate.from(v))) | |
.transform((v) => Temporal.PlainDate.from(v)), | |
} | |
/* | |
For use with tRPC after setting up superjson as a transforner | |
*/ | |
import superjson from "superjson" | |
superjson.registerCustom<Temporal.Instant, string>( | |
{ | |
isApplicable: (v): v is Temporal.Instant => v instanceof Temporal.Instant, | |
serialize: (v) => v.toJSON(), | |
deserialize: (v) => Temporal.Instant.from(v), | |
}, | |
"Temporal.Instant" | |
) | |
superjson.registerCustom<Temporal.ZonedDateTime, string>( | |
{ | |
isApplicable: (v): v is Temporal.ZonedDateTime => v instanceof Temporal.ZonedDateTime, | |
serialize: (v) => v.toJSON(), | |
deserialize: (v) => Temporal.ZonedDateTime.from(v), | |
}, | |
"Temporal.ZonedDateTime" | |
) | |
superjson.registerCustom<Temporal.PlainDate, string>( | |
{ | |
isApplicable: (v): v is Temporal.PlainDate => v instanceof Temporal.PlainDate, | |
serialize: (v) => v.toJSON(), | |
deserialize: (v) => Temporal.PlainDate.from(v), | |
}, | |
"Temporal.PlainDate" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where is attempt
attempt(() => )
coming from?