0.1.0 #1
47
src/jsonifiable/dejsonifySchemable.ts
Normal file
47
src/jsonifiable/dejsonifySchemable.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Effect, pipe } from "effect"
|
||||
import { z } from "zod"
|
||||
import { JsonifiableSchemableClass, JsonifiableSchemableConfig } from "."
|
||||
import { parseZodTypeEffect } from "../util"
|
||||
|
||||
|
||||
export const dejsonifySchemable = <
|
||||
C extends JsonifiableSchemableClass<$Config>,
|
||||
$Config extends JsonifiableSchemableConfig,
|
||||
>(
|
||||
class_: C | JsonifiableSchemableClass<$Config>,
|
||||
values: $Config["jsonifiedValues"],
|
||||
params?: Partial<z.ParseParams>,
|
||||
) =>
|
||||
new class_(class_.dejsonifySchema.parse(values, params)) as InstanceType<C>
|
||||
|
||||
|
||||
export const dejsonifySchemablePromise = async <
|
||||
C extends JsonifiableSchemableClass<$Config>,
|
||||
$Config extends JsonifiableSchemableConfig,
|
||||
>(
|
||||
class_: C | JsonifiableSchemableClass<$Config>,
|
||||
values: $Config["jsonifiedValues"],
|
||||
params?: Partial<z.ParseParams>,
|
||||
) =>
|
||||
new class_(await class_.dejsonifySchema.parseAsync(values, params)) as InstanceType<C>
|
||||
|
||||
|
||||
export const dejsonifySchemableEffect = <
|
||||
C extends JsonifiableSchemableClass<$Config>,
|
||||
$Config extends JsonifiableSchemableConfig,
|
||||
>(
|
||||
class_: C | JsonifiableSchemableClass<$Config>,
|
||||
values: $Config["jsonifiedValues"],
|
||||
params?: Partial<z.ParseParams>,
|
||||
) => pipe(
|
||||
parseZodTypeEffect<
|
||||
z.output<typeof class_.dejsonifySchema>,
|
||||
z.input<typeof class_.dejsonifySchema>
|
||||
>(
|
||||
class_.dejsonifySchema,
|
||||
values,
|
||||
params,
|
||||
),
|
||||
|
||||
Effect.map(values => new class_(values) as InstanceType<C>),
|
||||
)
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./JsonifiableSchemableClass"
|
||||
export * from "./dejsonifySchemable"
|
||||
export * from "./makeJsonifiableSchemableClass"
|
||||
export * from "./schema"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod"
|
||||
import { makeSchemableClass, newSchemable } from "."
|
||||
import { dejsonifyBigIntSchema, dejsonifySchemableSchema, jsonifyBigIntSchema, jsonifySchemableSchema, makeJsonifiableSchemableClass } from "./jsonifiable"
|
||||
import { dejsonifyBigIntSchema, dejsonifySchemable, dejsonifySchemableSchema, jsonifyBigIntSchema, jsonifySchemableSchema, makeJsonifiableSchemableClass } from "./jsonifiable"
|
||||
|
||||
|
||||
const GroupSchema = z.object({
|
||||
@@ -59,4 +59,6 @@ const group1 = new Group({ id: 1n, name: "Group 1" })
|
||||
const user1 = new User({ id: 1n, name: "User 1", group: group1 })
|
||||
const user2 = newSchemable(User, { id: 2n, name: "User 2", group: group1 })
|
||||
|
||||
console.log(user2.jsonify())
|
||||
const jsonifiedUser2 = user2.jsonify()
|
||||
const dejsonifiedUser2 = dejsonifySchemable(User, jsonifiedUser2)
|
||||
console.log(dejsonifiedUser2)
|
||||
|
||||
Reference in New Issue
Block a user