Jsonifiable

This commit is contained in:
Julien Valverdé
2024-01-01 23:14:08 +01:00
parent 92271583ce
commit 00040fb7df
9 changed files with 87 additions and 8 deletions

2
src/jsonifiable/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export * from "./makeJsonifiableSchemableClass"
export * from "./schema"

View File

@@ -1,7 +1,7 @@
import { JsonifiableObject } from "type-fest/source/jsonifiable"
import { z } from "zod"
import { SchemableClass, SchemableConfig } from "."
import { parseZodTypeEffect } from "./util"
import { SchemableClass, SchemableConfig } from ".."
import { parseZodTypeEffect } from "../util"
export function makeJsonifiableSchemableClass<

View File

@@ -0,0 +1,18 @@
import { z } from "zod"
export const jsonifyBigIntSchema = <S extends z.ZodBigInt>(schema: S) =>
schema.transform(v => v.toString())
export const dejsonifyBigIntSchema = <S extends z.ZodBigInt>(schema: S) =>
z
.string()
.transform(v => {
try {
return BigInt(v)
}
catch (e) {
return v
}
})
.pipe(schema)

View File

@@ -0,0 +1,18 @@
import { z } from "zod"
export const jsonifyDateSchema = <S extends z.ZodDate>(schema: S) =>
schema.transform(v => v.toString())
export const dejsonifyDateSchema = <S extends z.ZodDate>(schema: S) =>
z
.string()
.transform(v => {
try {
return new Date(v)
}
catch (e) {
return v
}
})
.pipe(schema)

View File

@@ -0,0 +1,19 @@
import { Decimal } from "decimal.js"
import { z } from "zod"
export const jsonifyDecimalSchema = <S extends z.ZodType<Decimal, z.ZodTypeDef, Decimal>>(schema: S) =>
schema.transform(v => v.toJSON())
export const dejsonifyDecimalSchema = <S extends z.ZodType<Decimal, z.ZodTypeDef, Decimal>>(schema: S) =>
z
.string()
.transform(v => {
try {
return new Decimal(v)
}
catch (e) {
return v
}
})
.pipe(schema)

View File

@@ -0,0 +1,3 @@
export * from "./bigint"
export * from "./date"
export * from "./decimal"

View File

@@ -8,9 +8,17 @@ const UserSchema = z.object({
})
const UserSchemaObject = makeSchemableClass({ schema: UserSchema })
const UserSchemableObject = makeSchemableClass({ schema: UserSchema })
class User extends UserSchemaObject {}
// const UserJsonifiableSchemableObject = makeJsonifiableSchemableClass(UserSchemableObject, {
// jsonifySchema: ({ schema, s }) => schema.extend({
// }),
// dejsonifySchema: ({ schema, s }) => schema.extend({
// }),
// })
class User extends UserSchemableObject {}
const user1 = new User({ id: 1n })
const user2 = newSchemable(User, { id: 2n })