Skip to content

Instantly share code, notes, and snippets.

@alexturpin
Last active May 2, 2024 14:00
Show Gist options
  • Save alexturpin/505a749a5e97792ea9d23ea50e02ab44 to your computer and use it in GitHub Desktop.
Save alexturpin/505a749a5e97792ea9d23ea50e02ab44 to your computer and use it in GitHub Desktop.
Temporal with Zod + tRPC
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"
)
@JonathonRP
Copy link

where is attempt attempt(() => ) coming from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment