Co-authored-by: Julien Valverdé <julien.valverde@mailo.com> Reviewed-on: https://git.jvalver.de/Thilawyn/schemable-class/pulls/1
This commit was merged in pull request #1.
This commit is contained in:
49
src/makeSchemableClass.ts
Normal file
49
src/makeSchemableClass.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { z } from "zod"
|
||||
import { SchemableClass, SchemableConfig } from "."
|
||||
import { zodObjectRemoveDefaults } from "./util"
|
||||
|
||||
|
||||
export function makeSchemableClass<
|
||||
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)
|
||||
|
||||
const $schemableConfig = {
|
||||
values: undefined as unknown as z.output<typeof schemaWithDefaultValues>,
|
||||
input: undefined as unknown as z.input<typeof schemaWithDefaultValues>,
|
||||
schema: undefined as unknown as typeof schema,
|
||||
schemaWithDefaultValues: undefined as unknown as typeof schemaWithDefaultValues,
|
||||
} as const satisfies SchemableConfig
|
||||
|
||||
return class SchemableObject {
|
||||
static readonly $schemableConfig = $schemableConfig
|
||||
static readonly schema = schema
|
||||
static readonly schemaWithDefaultValues = schemaWithDefaultValues
|
||||
|
||||
readonly $schemableConfig = $schemableConfig
|
||||
readonly schema = schema
|
||||
readonly schemaWithDefaultValues = schemaWithDefaultValues
|
||||
|
||||
constructor(data: z.output<typeof schema>) {
|
||||
Object.assign(this, data)
|
||||
}
|
||||
} as SchemableClass<typeof $schemableConfig>
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user