Skip to content

fix: support default values in generated zod schemas #914

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

Merged
merged 4 commits into from
Jan 1, 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
19 changes: 14 additions & 5 deletions packages/schema/src/plugins/zod/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { name } from '.';
import { getDefaultOutputFolder } from '../plugin-utils';
import Transformer from './transformer';
import removeDir from './utils/removeDir';
import { makeFieldSchema, makeValidationRefinements } from './utils/schema-gen';
import { makeFieldSchema, makeValidationRefinements, getFieldSchemaDefault } from './utils/schema-gen';

export async function generate(
model: Model,
Expand Down Expand Up @@ -309,7 +309,7 @@ async function generateModelSchema(model: DataModel, project: Project, output: s
writer.write(`const baseSchema = z.object(`);
writer.inlineBlock(() => {
scalarFields.forEach((field) => {
writer.writeLine(`${field.name}: ${makeFieldSchema(field)},`);
writer.writeLine(`${field.name}: ${makeFieldSchema(field, true)},`);
});
});
writer.writeLine(');');
Expand Down Expand Up @@ -356,7 +356,12 @@ async function generateModelSchema(model: DataModel, project: Project, output: s
////////////////////////////////////////////////
// 1. Model schema
////////////////////////////////////////////////
let modelSchema = makePartial('baseSchema');
const fieldsWithoutDefault = scalarFields.filter((f) => !getFieldSchemaDefault(f));
// mark fields without default value as optional
let modelSchema = makePartial(
'baseSchema',
fieldsWithoutDefault.length < scalarFields.length ? fieldsWithoutDefault.map((f) => f.name) : undefined
);

// omit fields
const fieldsToOmit = scalarFields.filter((field) => hasAttribute(field, '@omit'));
Expand Down Expand Up @@ -475,9 +480,13 @@ async function generateModelSchema(model: DataModel, project: Project, output: s

function makePartial(schema: string, fields?: string[]) {
if (fields) {
return `${schema}.partial({
${fields.map((f) => `${f}: true`).join(', ')},
if (fields.length === 0) {
return schema;
} else {
return `${schema}.partial({
${fields.map((f) => `${f}: true`).join(', ')}
})`;
}
} else {
return `${schema}.partial()`;
}
Expand Down
52 changes: 49 additions & 3 deletions packages/schema/src/plugins/zod/utils/schema-gen.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
import { ExpressionContext, PluginError, getAttributeArg, getAttributeArgLiteral, getLiteral } from '@zenstackhq/sdk';
import { DataModel, DataModelField, DataModelFieldAttribute, isDataModel, isEnum } from '@zenstackhq/sdk/ast';
import {
ExpressionContext,
PluginError,
getAttributeArg,
getAttributeArgLiteral,
getLiteral,
isFromStdlib,
} from '@zenstackhq/sdk';
import {
DataModel,
DataModelField,
DataModelFieldAttribute,
isDataModel,
isEnum,
isInvocationExpr,
isNumberLiteral,
isStringLiteral,
} from '@zenstackhq/sdk/ast';
import { upperCaseFirst } from 'upper-case-first';
import { name } from '..';
import {
TypeScriptExpressionTransformer,
TypeScriptExpressionTransformerError,
} from '../../../utils/typescript-expression-transformer';

export function makeFieldSchema(field: DataModelField) {
export function makeFieldSchema(field: DataModelField, respectDefault = false) {
if (isDataModel(field.type.reference?.ref)) {
if (field.type.array) {
// array field is always optional
Expand Down Expand Up @@ -108,6 +124,13 @@ export function makeFieldSchema(field: DataModelField) {
}
}

if (respectDefault) {
const schemaDefault = getFieldSchemaDefault(field);
if (schemaDefault) {
schema += `.default(${schemaDefault})`;
}
}

if (field.type.optional) {
schema += '.nullish()';
}
Expand Down Expand Up @@ -202,3 +225,26 @@ function refineDecimal(op: 'gt' | 'gte' | 'lt' | 'lte', value: number, messageAr
}
}${messageArg})`;
}

export function getFieldSchemaDefault(field: DataModelField) {
const attr = field.attributes.find((attr) => attr.decl.ref?.name === '@default');
if (!attr) {
return undefined;
}
const arg = attr.args.find((arg) => arg.$resolvedParam?.name === 'value');
if (arg) {
if (isStringLiteral(arg.value)) {
return JSON.stringify(arg.value.value);
} else if (isNumberLiteral(arg.value)) {
return arg.value.value;
} else if (
isInvocationExpr(arg.value) &&
isFromStdlib(arg.value.function.ref!) &&
arg.value.function.$refText === 'now'
) {
return `() => new Date()`;
}
}

return undefined;
}
2 changes: 1 addition & 1 deletion tests/integration/tests/regression/issue-864.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { loadSchema } from '@zenstackhq/testtools';

describe('Regression: issue nested create', () => {
describe('Regression: issue 864', () => {
it('safe create', async () => {
const { prisma, enhance } = await loadSchema(
`
Expand Down
22 changes: 22 additions & 0 deletions tests/integration/tests/regression/issue-886.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { loadSchema } from '@zenstackhq/testtools';

describe('Regression: issue 886', () => {
it('regression', async () => {
const { zodSchemas } = await loadSchema(
`
model Model {
id Int @id @default(autoincrement())
a Int @default(100)
b String @default('')
c DateTime @default(now())
}
`
);

const r = zodSchemas.models.ModelSchema.parse({});
expect(r.a).toBe(100);
expect(r.b).toBe('');
expect(r.c).toBeInstanceOf(Date);
expect(r.id).toBeUndefined();
});
});