Skip to content

Commit 44a6f9e

Browse files
authored
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)
1 parent b8209d7 commit 44a6f9e

5 files changed

Lines changed: 461 additions & 104 deletions

File tree

‎BREAKINGCHANGES.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@
33
1. non-optional to-one relation doesn't automatically filter parent read when evaluating access policies
44
1. `@omit` and `@password` attributes have been removed
55
1. SWR plugin is removed
6+
1. `makeModelSchema()` no longer includes relation fields by default — use `include` or `select` options to opt in, mirroring ORM behaviour

‎packages/zod/src/factory.ts‎

Lines changed: 77 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,10 @@ export function createSchemaFactory<Schema extends SchemaDef>(schema: Schema) {
3434

3535
/** Internal untyped representation of the options object used at runtime. */
3636
type RawOptions = {
37-
select?: Record<string, unknown>;
38-
include?: Record<string, unknown>;
39-
omit?: Record<string, unknown>;
37+
select?: Record<string, true | RawOptions>;
38+
include?: Record<string, true | RawOptions>;
39+
omit?: Record<string, true>;
40+
optionality?: 'all' | 'defaults';
4041
};
4142

4243
/**
@@ -49,10 +50,11 @@ type RawOptions = {
4950
*/
5051
const rawOptionsSchema: z.ZodType<RawOptions> = z.lazy(() =>
5152
z
52-
.object({
53-
select: z.record(z.string(), z.union([z.boolean(), rawOptionsSchema])).optional(),
54-
include: z.record(z.string(), z.union([z.boolean(), rawOptionsSchema])).optional(),
55-
omit: z.record(z.string(), z.boolean()).optional(),
53+
.strictObject({
54+
select: z.record(z.string(), z.union([z.literal(true), rawOptionsSchema])).optional(),
55+
include: z.record(z.string(), z.union([z.literal(true), rawOptionsSchema])).optional(),
56+
omit: z.record(z.string(), z.literal(true)).optional(),
57+
optionality: z.enum(['all', 'defaults']).optional(),
5658
})
5759
.superRefine((val, ctx) => {
5860
if (val.select && val.include) {
@@ -93,26 +95,16 @@ class SchemaFactory<Schema extends SchemaDef> {
9395
const modelDef = this.schema.requireModel(model);
9496

9597
if (!options) {
96-
// ── No-options path (original behaviour) ─────────────────────────
98+
// ── No-options path: scalar fields only (relations excluded by default) ──
9799
const fields: Record<string, z.ZodType> = {};
98100

99101
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
100-
if (fieldDef.relation) {
101-
const relatedModelName = fieldDef.type;
102-
const lazySchema: z.ZodType = z.lazy(() =>
103-
this.makeModelSchema(relatedModelName as GetModels<Schema>),
104-
);
105-
// relation fields are always optional
106-
fields[fieldName] = this.applyDescription(
107-
this.applyCardinality(lazySchema, fieldDef).optional(),
108-
fieldDef.attributes,
109-
);
110-
} else {
111-
fields[fieldName] = this.applyDescription(
112-
this.makeScalarFieldSchema(fieldDef),
113-
fieldDef.attributes,
114-
);
115-
}
102+
// Relation fields are excluded by default — use `include` or `select`
103+
// to opt in, mirroring ORM behaviour and avoiding infinite
104+
// nesting for circular relations.
105+
if (fieldDef.relation) continue;
106+
107+
fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
116108
}
117109

118110
const shape = z.strictObject(fields);
@@ -125,7 +117,8 @@ class SchemaFactory<Schema extends SchemaDef> {
125117
// ── Options path ─────────────────────────────────────────────────────
126118
const rawOptions = rawOptionsSchema.parse(options);
127119
const fields = this.buildFieldsWithOptions(model as string, rawOptions);
128-
const shape = z.strictObject(fields);
120+
const optionalizedFields = this.applyOptionality(fields, model as string, rawOptions.optionality);
121+
const shape = z.strictObject(optionalizedFields);
129122
// @@validate conditions only reference scalar fields of the same model
130123
// (the ZModel compiler rejects relation fields). When `select` or `omit`
131124
// produces a partial shape some of those scalar fields may be absent;
@@ -139,6 +132,9 @@ class SchemaFactory<Schema extends SchemaDef> {
139132
>;
140133
}
141134

135+
/**
136+
* @deprecated Use `makeModelSchema(model, { optionality: 'defaults' })` instead.
137+
*/
142138
makeModelCreateSchema<Model extends GetModels<Schema>>(
143139
model: Model,
144140
): z.ZodObject<GetModelCreateFieldsShape<Schema, Model>, z.core.$strict> {
@@ -165,6 +161,9 @@ class SchemaFactory<Schema extends SchemaDef> {
165161
) as unknown as z.ZodObject<GetModelCreateFieldsShape<Schema, Model>, z.core.$strict>;
166162
}
167163

164+
/**
165+
* @deprecated Use `makeModelSchema(model, { optionality: 'all' })` instead.
166+
*/
168167
makeModelUpdateSchema<Model extends GetModels<Schema>>(
169168
model: Model,
170169
): z.ZodObject<GetModelUpdateFieldsShape<Schema, Model>, z.core.$strict> {
@@ -193,6 +192,41 @@ class SchemaFactory<Schema extends SchemaDef> {
193192
// Options-aware field building
194193
// -------------------------------------------------------------------------
195194

195+
/**
196+
* Applies the `optionality` option to a fields map.
197+
*
198+
* - `"all"` — wraps every field in `z.ZodOptional`.
199+
* - `"defaults"` — only wraps fields that have a `@default` attribute or
200+
* are `@updatedAt` in `z.ZodOptional`. Fields that are
201+
* already optional (nullable optional) retain their shape;
202+
* we just add the outer optional layer.
203+
* - `undefined` — returns the fields map unchanged.
204+
*/
205+
private applyOptionality(
206+
fields: Record<string, z.ZodType>,
207+
model: string,
208+
optionality: 'all' | 'defaults' | undefined,
209+
): Record<string, z.ZodType> {
210+
if (!optionality) return fields;
211+
212+
const modelDef = this.schema.requireModel(model);
213+
const result: Record<string, z.ZodType> = {};
214+
215+
for (const [fieldName, fieldSchema] of Object.entries(fields)) {
216+
if (optionality === 'all') {
217+
result[fieldName] = this.wrapOptionalPreservingMeta(fieldSchema);
218+
} else {
219+
// optionality === 'defaults'
220+
const fieldDef = modelDef.fields[fieldName];
221+
const hasDefault =
222+
fieldDef && (fieldDef.default !== undefined || fieldDef.updatedAt || fieldDef.optional);
223+
result[fieldName] = hasDefault ? this.wrapOptionalPreservingMeta(fieldSchema) : fieldSchema;
224+
}
225+
}
226+
227+
return result;
228+
}
229+
196230
/**
197231
* Internal loose options shape used at runtime (we've already validated the
198232
* type-level constraints via the overload signatures).
@@ -204,10 +238,8 @@ class SchemaFactory<Schema extends SchemaDef> {
204238

205239
if (select) {
206240
// ── select branch ────────────────────────────────────────────────
207-
// Only include fields that are explicitly listed with a truthy value.
241+
// Only include fields that are explicitly listed (value is always `true` or nested options).
208242
for (const [key, value] of Object.entries(select)) {
209-
if (!value) continue; // false → skip
210-
211243
const fieldDef = modelDef.fields[key];
212244
if (!fieldDef) {
213245
throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
@@ -257,8 +289,6 @@ class SchemaFactory<Schema extends SchemaDef> {
257289
// Validate include keys and add relation fields.
258290
if (include) {
259291
for (const [key, value] of Object.entries(include)) {
260-
if (!value) continue; // false → skip
261-
262292
const fieldDef = modelDef.fields[key];
263293
if (!fieldDef) {
264294
throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
@@ -296,9 +326,8 @@ class SchemaFactory<Schema extends SchemaDef> {
296326
const fields = new Set<string>();
297327

298328
if (select) {
299-
// Only scalar fields explicitly selected with a truthy value.
300-
for (const [key, value] of Object.entries(select)) {
301-
if (!value) continue;
329+
// Only scalar fields explicitly selected (value is always `true` or nested options).
330+
for (const key of Object.keys(select)) {
302331
const fieldDef = modelDef.fields[key];
303332
if (fieldDef && !fieldDef.relation) {
304333
fields.add(key);
@@ -403,6 +432,21 @@ class SchemaFactory<Schema extends SchemaDef> {
403432
]);
404433
}
405434

435+
/**
436+
* Wraps a schema with `.optional()` and copies any `description` from its
437+
* metadata onto the resulting `ZodOptional`, so that callers inspecting
438+
* `.meta()?.description` on shape fields still find the value after
439+
* optionality has been applied.
440+
*/
441+
private wrapOptionalPreservingMeta(schema: z.ZodType): z.ZodType {
442+
const optional = schema.optional();
443+
const description = schema.meta()?.description as string | undefined;
444+
if (description) {
445+
return optional.meta({ description });
446+
}
447+
return optional;
448+
}
449+
406450
private applyCardinality(schema: z.ZodType, fieldDef: FieldDef): z.ZodType {
407451
let result = schema;
408452
if (fieldDef.array) {

0 commit comments

Comments
 (0)