Jsonifiable schemas
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Julien Valverdé
2024-02-22 23:59:28 +01:00
parent 68b39f4997
commit 6c6e2cce7c
5 changed files with 112 additions and 2 deletions

View File

@@ -0,0 +1,28 @@
import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
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)
)
}

View File

@@ -0,0 +1,28 @@
import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
export type JsonifiedDate = Opaque<string, "@thilawyn/schemable-class/JsonifiedDate">
export function jsonifyDateSchema<S extends z.ZodDate>(schema: S) {
return schema.transform(v => v.toString() as JsonifiedDate)
}
export function dejsonifyDateSchema<S extends z.ZodDate>(schema: S) {
return z
.custom<JsonifiedDate>(identity)
.pipe(z
.string()
.transform(v => {
try {
return new Date(v)
}
catch (e) {
return v
}
})
.pipe(schema)
)
}

View File

@@ -0,0 +1,33 @@
import { Decimal } from "decimal.js"
import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
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)
)
}

View File

@@ -0,0 +1,16 @@
import { dejsonifyBigIntSchema, jsonifyBigIntSchema } from "./bigint"
import { dejsonifyDateSchema, jsonifyDateSchema } from "./date"
import { dejsonifyDecimalSchema, jsonifyDecimalSchema } from "./decimal"
export const jsonify = {
bigint: jsonifyBigIntSchema,
date: jsonifyDateSchema,
decimal: jsonifyDecimalSchema,
}
export const dejsonify = {
bigint: dejsonifyBigIntSchema,
date: dejsonifyDateSchema,
decimal: dejsonifyDecimalSchema,
}