Skip to content
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

feat: non-strict mode for zod plugin #1697

Merged
merged 2 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions packages/schema/src/plugins/zod/generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
PluginError,
PluginGlobalOptions,
PluginOptions,
RUNTIME_PACKAGE,
Expand Down Expand Up @@ -54,6 +55,17 @@ export class ZodSchemaGenerator {
ensureEmptyDir(output);
Transformer.setOutputPath(output);

// options validation
if (
this.options.mode &&
(typeof this.options.mode !== 'string' || !['strip', 'strict', 'passthrough'].includes(this.options.mode))
) {
throw new PluginError(
name,
`Invalid mode option: "${this.options.mode}". Must be one of 'strip', 'strict', or 'passthrough'.`
);
}

// calculate the models to be excluded
const excludeModels = this.getExcludedModels();

Expand Down Expand Up @@ -322,7 +334,19 @@ export class ZodSchemaGenerator {
writer.writeLine(`${field.name}: ${makeFieldSchema(field)},`);
});
});
writer.writeLine(');');

switch (this.options.mode) {
case 'strip':
// zod strips by default
writer.writeLine(')');
break;
case 'passthrough':
writer.writeLine(').passthrough();');
break;
default:
writer.writeLine(').strict();');
break;
}

// relation fields

Expand Down Expand Up @@ -463,7 +487,7 @@ export const ${upperCaseFirst(model.name)}PrismaCreateSchema = ${prismaCreateSch
})
.join(',\n')}
})`;
prismaUpdateSchema = this.makePartial(prismaUpdateSchema);
prismaUpdateSchema = this.makePassthrough(this.makePartial(prismaUpdateSchema));
writer.writeLine(
`
/**
Expand Down
66 changes: 43 additions & 23 deletions packages/schema/src/plugins/zod/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ export default class Transformer {

prepareObjectSchema(zodObjectSchemaFields: string[], options: PluginOptions) {
const objectSchema = `${this.generateExportObjectSchemaStatement(
this.addFinalWrappers({ zodStringFields: zodObjectSchemaFields })
this.wrapWithZodObject(zodObjectSchemaFields, options.mode as string)
)}\n`;

const prismaImportStatement = this.generateImportPrismaStatement(options);
Expand All @@ -314,12 +314,6 @@ export default class Transformer {
export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
}

addFinalWrappers({ zodStringFields }: { zodStringFields: string[] }) {
const fields = [...zodStringFields];

return this.wrapWithZodObject(fields) + '.strict()';
}

generateImportPrismaStatement(options: PluginOptions) {
const prismaClientImportPath = computePrismaClientImport(
path.resolve(Transformer.outputPath, './objects'),
Expand Down Expand Up @@ -408,14 +402,26 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
return wrapped;
}

wrapWithZodObject(zodStringFields: string | string[]) {
wrapWithZodObject(zodStringFields: string | string[], mode = 'strict') {
let wrapped = '';

wrapped += 'z.object({';
wrapped += '\n';
wrapped += ' ' + zodStringFields;
wrapped += '\n';
wrapped += '})';

switch (mode) {
case 'strip':
// zod strips by default
break;
case 'passthrough':
wrapped += '.passthrough()';
break;
default:
wrapped += '.strict()';
break;
}
return wrapped;
}

Expand Down Expand Up @@ -465,6 +471,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
];
let codeBody = '';
const operations: [string, string][] = [];
const mode = (options.mode as string) ?? 'strict';

// OrderByWithRelationInput's name is different when "fullTextSearch" is enabled
const orderByWithRelationInput = this.inputObjectTypes
Expand All @@ -477,7 +484,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
imports.push(
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`
);
codeBody += `findUnique: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema`;
codeBody += `findUnique: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['findUnique', origModelName]);
}

Expand All @@ -488,7 +496,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`,
`import { ${modelName}ScalarFieldEnumSchema } from '../enums/${modelName}ScalarFieldEnum.schema'`
);
codeBody += `findFirst: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional() }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional()`;
codeBody += `findFirst: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['findFirst', origModelName]);
}

Expand All @@ -499,7 +508,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`,
`import { ${modelName}ScalarFieldEnumSchema } from '../enums/${modelName}ScalarFieldEnum.schema'`
);
codeBody += `findMany: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional() }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional()`;
codeBody += `findMany: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['findMany', origModelName]);
}

Expand All @@ -515,31 +525,35 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
const dataSchema = generateUnchecked
? `z.union([${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema])`
: `${modelName}CreateInputObjectSchema`;
codeBody += `create: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: ${dataSchema} }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: ${dataSchema}`;
codeBody += `create: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['create', origModelName]);
}

if (createMany && supportCreateMany(zmodel)) {
imports.push(
`import { ${modelName}CreateManyInputObjectSchema } from '../objects/${modelName}CreateManyInput.schema'`
);
codeBody += `createMany: z.object({ data: z.union([${modelName}CreateManyInputObjectSchema, z.array(${modelName}CreateManyInputObjectSchema)]), skipDuplicates: z.boolean().optional() }),`;
const fields = `data: z.union([${modelName}CreateManyInputObjectSchema, z.array(${modelName}CreateManyInputObjectSchema)]), skipDuplicates: z.boolean().optional()`;
codeBody += `createMany: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['createMany', origModelName]);
}

if (deleteOne) {
imports.push(
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`
);
codeBody += `'delete': z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema`;
codeBody += `'delete': ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['delete', origModelName]);
}

if (deleteMany) {
imports.push(
`import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'`
);
codeBody += `deleteMany: z.object({ where: ${modelName}WhereInputObjectSchema.optional() }),`;
const fields = `where: ${modelName}WhereInputObjectSchema.optional()`;
codeBody += `deleteMany: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['deleteMany', origModelName]);
}

Expand All @@ -556,7 +570,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
const dataSchema = generateUnchecked
? `z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema])`
: `${modelName}UpdateInputObjectSchema`;
codeBody += `update: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: ${dataSchema}, where: ${modelName}WhereUniqueInputObjectSchema }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: ${dataSchema}, where: ${modelName}WhereUniqueInputObjectSchema`;
codeBody += `update: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['update', origModelName]);
}

Expand All @@ -573,7 +588,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
const dataSchema = generateUnchecked
? `z.union([${modelName}UpdateManyMutationInputObjectSchema, ${modelName}UncheckedUpdateManyInputObjectSchema])`
: `${modelName}UpdateManyMutationInputObjectSchema`;
codeBody += `updateMany: z.object({ data: ${dataSchema}, where: ${modelName}WhereInputObjectSchema.optional() }),`;
const fields = `data: ${dataSchema}, where: ${modelName}WhereInputObjectSchema.optional()`;
codeBody += `updateMany: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['updateMany', origModelName]);
}

Expand All @@ -595,7 +611,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
const updateSchema = generateUnchecked
? `z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema])`
: `${modelName}UpdateInputObjectSchema`;
codeBody += `upsert: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema, create: ${createSchema}, update: ${updateSchema} }),`;
const fields = `${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema, create: ${createSchema}, update: ${updateSchema}`;
codeBody += `upsert: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['upsert', origModelName]);
}

Expand Down Expand Up @@ -641,9 +658,10 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`
);

codeBody += `aggregate: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), ${aggregateOperations.join(
const fields = `where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), ${aggregateOperations.join(
', '
)} }),`;
)}`;
codeBody += `aggregate: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['aggregate', modelName]);
}

Expand All @@ -654,9 +672,10 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
`import { ${modelName}ScalarWhereWithAggregatesInputObjectSchema } from '../objects/${modelName}ScalarWhereWithAggregatesInput.schema'`,
`import { ${modelName}ScalarFieldEnumSchema } from '../enums/${modelName}ScalarFieldEnum.schema'`
);
codeBody += `groupBy: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithAggregationInputObjectSchema, ${modelName}OrderByWithAggregationInputObjectSchema.array()]).optional(), having: ${modelName}ScalarWhereWithAggregatesInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), by: z.array(${modelName}ScalarFieldEnumSchema), ${aggregateOperations.join(
const fields = `where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithAggregationInputObjectSchema, ${modelName}OrderByWithAggregationInputObjectSchema.array()]).optional(), having: ${modelName}ScalarWhereWithAggregatesInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), by: z.array(${modelName}ScalarFieldEnumSchema), ${aggregateOperations.join(
', '
)} }),`;
)}`;
codeBody += `groupBy: ${this.wrapWithZodObject(fields, mode)},`;

operations.push(['groupBy', origModelName]);
}
Expand All @@ -671,7 +690,8 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`;
`import { ${modelName}CountAggregateInputObjectSchema } from '../objects/${modelName}CountAggregateInput.schema'`
);

codeBody += `count: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional(), select: z.union([ z.literal(true), ${modelName}CountAggregateInputObjectSchema ]).optional() })`;
const fields = `where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${orderByWithRelationInput}ObjectSchema, ${orderByWithRelationInput}ObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional(), select: z.union([ z.literal(true), ${modelName}CountAggregateInputObjectSchema ]).optional()`;
codeBody += `count: ${this.wrapWithZodObject(fields, mode)},`;
operations.push(['count', origModelName]);
}

Expand Down
Loading
Loading