29 lines
735 B
TypeScript
29 lines
735 B
TypeScript
import { identity } from "lodash-es"
|
|
import { Opaque } from "type-fest"
|
|
import { z } from "zod"
|
|
|
|
|
|
export type JsonifiedBigInt = Opaque<string, "@thilawyn/zod-schema-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)
|
|
)
|
|
}
|