34 lines
856 B
TypeScript
34 lines
856 B
TypeScript
import { Decimal } from "decimal.js"
|
|
import { Opaque } from "type-fest"
|
|
import { z } from "zod"
|
|
import { identity } from "../../../util"
|
|
|
|
|
|
export type JsonifiedDecimal = Opaque<string, "@thilawyn/schemable-class/JsonifiedDecimal">
|
|
|
|
|
|
export function jsonifyDecimalSchema<
|
|
S extends z.ZodType<Decimal, z.ZodTypeDef, Decimal>
|
|
>(schema: S) {
|
|
return schema.transform(v => v.toJSON() as JsonifiedDecimal)
|
|
}
|
|
|
|
export function dejsonifyDecimalSchema<
|
|
S extends z.ZodType<Decimal, z.ZodTypeDef, Decimal>
|
|
>(schema: S) {
|
|
return z
|
|
.custom<JsonifiedDecimal>(identity)
|
|
.pipe(z
|
|
.string()
|
|
.transform(v => {
|
|
try {
|
|
return new Decimal(v)
|
|
}
|
|
catch (e) {
|
|
return v
|
|
}
|
|
})
|
|
.pipe(schema)
|
|
)
|
|
}
|