0.1.0 #1

Merged
Thilawyn merged 24 commits from next into master 2024-01-05 00:39:33 +01:00
5 changed files with 72 additions and 0 deletions
Showing only changes of commit 54de41cf97 - Show all commits

BIN
bun.lockb

Binary file not shown.

View File

@@ -0,0 +1 @@
export * from "./makeSchemaClass"

48
src/makeSchemaClass.ts Normal file
View File

@@ -0,0 +1,48 @@
import { Class } from "type-fest"
import { z } from "zod"
import { StaticMembers, zodObjectRemoveDefaults } from "./util"
export function makeSchemaClass<
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesOutput extends SchemaWithDefaultValuesInput, // TODO: apply "StripSchemaInputDefaults"?
SchemaWithDefaultValuesInput extends {},
>(
{
schema: schemaWithDefaultValues
}: {
schema: z.ZodObject<
SchemaWithDefaultValuesT,
SchemaWithDefaultValuesUnknownKeys,
SchemaWithDefaultValuesCatchall,
SchemaWithDefaultValuesOutput,
SchemaWithDefaultValuesInput
>
}
) {
const schema = zodObjectRemoveDefaults(schemaWithDefaultValues)
class SchemaObject {
static readonly schema = schema
static readonly schemaWithDefaultValues = schemaWithDefaultValues
readonly schema = schema
readonly schemaWithDefaultValues = schemaWithDefaultValues
constructor(data: z.output<typeof schema>) {
Object.assign(this, data)
}
}
return SchemaObject as (
Class<
SchemaObject & z.output<typeof schema>,
ConstructorParameters<typeof SchemaObject>
> &
StaticMembers<typeof SchemaObject>
)
}

14
src/tests.ts Normal file
View File

@@ -0,0 +1,14 @@
import { z } from "zod"
import { makeSchemaClass } from "./makeSchemaClass"
const UserSchema = z.object({
/** User ID */
id: z.bigint().default(-1n)
})
const UserSchemaObject = makeSchemaClass({ schema: UserSchema })
const user = new UserSchemaObject({ id: 1n })
user.id

View File

@@ -3,6 +3,15 @@ import { mapValues } from "lodash-es"
import { z } from "zod" import { z } from "zod"
/**
* Represents the static members of a class.
* @template C - The class type.
*/
export type StaticMembers<C> = {
[Key in keyof C as Key extends "prototype" ? never : Key]: C[Key]
}
/** /**
* Removes default values from a ZodObject schema and returns a new schema. * Removes default values from a ZodObject schema and returns a new schema.
* *