-
-
Notifications
You must be signed in to change notification settings - Fork 139
feat(zod): enforce literal true for select/include/omit options + exclude relation fields from makeModelSchema by default + add "optionality" setting to control runtime optionality of fields #2525
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
marcsigmund
wants to merge
7
commits into
zenstackhq:dev
Choose a base branch
from
marcsigmund:feat/zod-make-model-schema
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+454
−104
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
402842e
refactor(zod): enforce literal `true` for select/include/omit options
marcsigmund ef51472
feat(zod): exclude relation fields from makeModelSchema by default
marcsigmund 7ff42d4
fix(zod): address PR review comments
marcsigmund 28f9696
feat(zod): add optionality option to control optional field generation
marcsigmund 4cd3293
test(zod): add comprehensive tests for optionality option in makeMode…
marcsigmund 5de0984
refactor(zod): deprecate makeModelCreateSchema and makeModelUpdateSch…
marcsigmund f74bf75
refactor(zod): reorganize optionality tests to focus on type inference
marcsigmund File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,9 +34,10 @@ export function createSchemaFactory<Schema extends SchemaDef>(schema: Schema) { | |
|
|
||
| /** Internal untyped representation of the options object used at runtime. */ | ||
| type RawOptions = { | ||
| select?: Record<string, unknown>; | ||
| include?: Record<string, unknown>; | ||
| omit?: Record<string, unknown>; | ||
| select?: Record<string, true | RawOptions>; | ||
| include?: Record<string, true | RawOptions>; | ||
| omit?: Record<string, true>; | ||
| optionality?: 'all' | 'defaults'; | ||
| }; | ||
|
|
||
| /** | ||
|
|
@@ -49,10 +50,11 @@ type RawOptions = { | |
| */ | ||
| const rawOptionsSchema: z.ZodType<RawOptions> = z.lazy(() => | ||
| z | ||
| .object({ | ||
| select: z.record(z.string(), z.union([z.boolean(), rawOptionsSchema])).optional(), | ||
| include: z.record(z.string(), z.union([z.boolean(), rawOptionsSchema])).optional(), | ||
| omit: z.record(z.string(), z.boolean()).optional(), | ||
| .strictObject({ | ||
| select: z.record(z.string(), z.union([z.literal(true), rawOptionsSchema])).optional(), | ||
| include: z.record(z.string(), z.union([z.literal(true), rawOptionsSchema])).optional(), | ||
| omit: z.record(z.string(), z.literal(true)).optional(), | ||
| optionality: z.enum(['all', 'defaults']).optional(), | ||
| }) | ||
| .superRefine((val, ctx) => { | ||
| if (val.select && val.include) { | ||
|
|
@@ -93,26 +95,16 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| const modelDef = this.schema.requireModel(model); | ||
|
|
||
| if (!options) { | ||
| // ── No-options path (original behaviour) ───────────────────────── | ||
| // ── No-options path: scalar fields only (relations excluded by default) ── | ||
| const fields: Record<string, z.ZodType> = {}; | ||
|
|
||
| for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) { | ||
| if (fieldDef.relation) { | ||
| const relatedModelName = fieldDef.type; | ||
| const lazySchema: z.ZodType = z.lazy(() => | ||
| this.makeModelSchema(relatedModelName as GetModels<Schema>), | ||
| ); | ||
| // relation fields are always optional | ||
| fields[fieldName] = this.applyDescription( | ||
| this.applyCardinality(lazySchema, fieldDef).optional(), | ||
| fieldDef.attributes, | ||
| ); | ||
| } else { | ||
| fields[fieldName] = this.applyDescription( | ||
| this.makeScalarFieldSchema(fieldDef), | ||
| fieldDef.attributes, | ||
| ); | ||
| } | ||
| // Relation fields are excluded by default — use `include` or `select` | ||
| // to opt in, mirroring ORM behaviour and avoiding infinite | ||
| // nesting for circular relations. | ||
| if (fieldDef.relation) continue; | ||
|
|
||
| fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes); | ||
| } | ||
|
|
||
| const shape = z.strictObject(fields); | ||
|
|
@@ -125,7 +117,8 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| // ── Options path ───────────────────────────────────────────────────── | ||
| const rawOptions = rawOptionsSchema.parse(options); | ||
| const fields = this.buildFieldsWithOptions(model as string, rawOptions); | ||
| const shape = z.strictObject(fields); | ||
| const optionalizedFields = this.applyOptionality(fields, model as string, rawOptions.optionality); | ||
| const shape = z.strictObject(optionalizedFields); | ||
| // @@validate conditions only reference scalar fields of the same model | ||
| // (the ZModel compiler rejects relation fields). When `select` or `omit` | ||
| // produces a partial shape some of those scalar fields may be absent; | ||
|
|
@@ -139,6 +132,9 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| >; | ||
| } | ||
|
|
||
| /** | ||
| * @deprecated Use `makeModelSchema(model, { optionality: 'defaults' })` instead. | ||
| */ | ||
| makeModelCreateSchema<Model extends GetModels<Schema>>( | ||
| model: Model, | ||
| ): z.ZodObject<GetModelCreateFieldsShape<Schema, Model>, z.core.$strict> { | ||
|
|
@@ -165,6 +161,9 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| ) as unknown as z.ZodObject<GetModelCreateFieldsShape<Schema, Model>, z.core.$strict>; | ||
| } | ||
|
|
||
| /** | ||
| * @deprecated Use `makeModelSchema(model, { optionality: 'all' })` instead. | ||
| */ | ||
| makeModelUpdateSchema<Model extends GetModels<Schema>>( | ||
| model: Model, | ||
| ): z.ZodObject<GetModelUpdateFieldsShape<Schema, Model>, z.core.$strict> { | ||
|
|
@@ -193,6 +192,41 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| // Options-aware field building | ||
| // ------------------------------------------------------------------------- | ||
|
|
||
| /** | ||
| * Applies the `optionality` option to a fields map. | ||
| * | ||
| * - `"all"` — wraps every field in `z.ZodOptional`. | ||
| * - `"defaults"` — only wraps fields that have a `@default` attribute or | ||
| * are `@updatedAt` in `z.ZodOptional`. Fields that are | ||
| * already optional (nullable optional) retain their shape; | ||
| * we just add the outer optional layer. | ||
| * - `undefined` — returns the fields map unchanged. | ||
| */ | ||
| private applyOptionality( | ||
| fields: Record<string, z.ZodType>, | ||
| model: string, | ||
| optionality: 'all' | 'defaults' | undefined, | ||
| ): Record<string, z.ZodType> { | ||
| if (!optionality) return fields; | ||
|
|
||
| const modelDef = this.schema.requireModel(model); | ||
| const result: Record<string, z.ZodType> = {}; | ||
|
|
||
| for (const [fieldName, fieldSchema] of Object.entries(fields)) { | ||
| if (optionality === 'all') { | ||
| result[fieldName] = this.wrapOptionalPreservingMeta(fieldSchema); | ||
| } else { | ||
| // optionality === 'defaults' | ||
| const fieldDef = modelDef.fields[fieldName]; | ||
| const hasDefault = | ||
| fieldDef && (fieldDef.default !== undefined || fieldDef.updatedAt || fieldDef.optional); | ||
| result[fieldName] = hasDefault ? this.wrapOptionalPreservingMeta(fieldSchema) : fieldSchema; | ||
| } | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Internal loose options shape used at runtime (we've already validated the | ||
| * type-level constraints via the overload signatures). | ||
|
|
@@ -204,10 +238,8 @@ class SchemaFactory<Schema extends SchemaDef> { | |
|
|
||
| if (select) { | ||
| // ── select branch ──────────────────────────────────────────────── | ||
| // Only include fields that are explicitly listed with a truthy value. | ||
| // Only include fields that are explicitly listed (value is always `true` or nested options). | ||
| for (const [key, value] of Object.entries(select)) { | ||
| if (!value) continue; // false → skip | ||
|
|
||
| const fieldDef = modelDef.fields[key]; | ||
| if (!fieldDef) { | ||
| throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`); | ||
|
|
@@ -257,8 +289,6 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| // Validate include keys and add relation fields. | ||
| if (include) { | ||
| for (const [key, value] of Object.entries(include)) { | ||
| if (!value) continue; // false → skip | ||
|
|
||
| const fieldDef = modelDef.fields[key]; | ||
| if (!fieldDef) { | ||
| throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`); | ||
|
|
@@ -296,9 +326,8 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| const fields = new Set<string>(); | ||
|
|
||
| if (select) { | ||
| // Only scalar fields explicitly selected with a truthy value. | ||
| for (const [key, value] of Object.entries(select)) { | ||
| if (!value) continue; | ||
| // Only scalar fields explicitly selected (value is always `true` or nested options). | ||
| for (const [key] of Object.entries(select)) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Change to |
||
| const fieldDef = modelDef.fields[key]; | ||
| if (fieldDef && !fieldDef.relation) { | ||
| fields.add(key); | ||
|
|
@@ -403,6 +432,21 @@ class SchemaFactory<Schema extends SchemaDef> { | |
| ]); | ||
| } | ||
|
|
||
| /** | ||
| * Wraps a schema with `.optional()` and copies any `description` from its | ||
| * metadata onto the resulting `ZodOptional`, so that callers inspecting | ||
| * `.meta()?.description` on shape fields still find the value after | ||
| * optionality has been applied. | ||
| */ | ||
| private wrapOptionalPreservingMeta(schema: z.ZodType): z.ZodType { | ||
| const optional = schema.optional(); | ||
| const description = schema.meta()?.description as string | undefined; | ||
| if (description) { | ||
| return optional.meta({ description }); | ||
| } | ||
| return optional; | ||
| } | ||
|
|
||
| private applyCardinality(schema: z.ZodType, fieldDef: FieldDef): z.ZodType { | ||
| let result = schema; | ||
| if (fieldDef.array) { | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.