Files
zod-schema-class/src/jsonifiable/schema/bigint.ts
Julien Valverdé 019066bb9c
All checks were successful
continuous-integration/drone/push Build is passing
0.1.1 (#2)
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/schemable-class/pulls/2
2024-01-17 20:47:13 +01:00

29 lines
735 B
TypeScript

import { Opaque } from "type-fest"
import { z } from "zod"
import { identity } from "../../util"
export type JsonifiedBigInt = Opaque<string, "@thilawyn/schemable-class/JsonifiedBigInt">
export function jsonifyBigIntSchema<S extends z.ZodBigInt>(schema: S) {
return schema.transform(v => v.toString() as JsonifiedBigInt)
}
export function dejsonifyBigIntSchema<S extends z.ZodBigInt>(schema: S) {
return z
.custom<JsonifiedBigInt>(identity)
.pipe(z
.string()
.transform(v => {
try {
return BigInt(v)
}
catch (e) {
return v
}
})
.pipe(schema)
)
}