Skip to content

Commit

Permalink
fix: make sure zod schemas have type annotations (zenstackhq#574)
Browse files Browse the repository at this point in the history
  • Loading branch information
ymc9 authored Jul 10, 2023
1 parent 1e1ad8f commit 51985b1
Show file tree
Hide file tree
Showing 26 changed files with 369 additions and 252 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ dist
.env.local
.npmcache
coverage
.build
2 changes: 1 addition & 1 deletion packages/language/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"generate": "langium generate",
"watch": "concurrently \"langium generate --watch\" \"tsc --watch\"",
"lint": "eslint src --ext ts",
"build": "pnpm lint && pnpm clean && pnpm generate && tsc && copyfiles -F ./README.md ./LICENSE ./package.json dist",
"build": "pnpm lint && pnpm clean && pnpm generate && tsc && copyfiles -F ./README.md ./LICENSE ./package.json dist && pnpm pack dist --pack-destination '../../../.build'",
"prepublishOnly": "pnpm build",
"publish-dev": "pnpm build && pnpm publish --tag dev"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/openapi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"scripts": {
"clean": "rimraf dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE dist && copyfiles -u 1 ./src/plugin.zmodel dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE dist && copyfiles -u 1 ./src/plugin.zmodel dist && pnpm pack dist --pack-destination '../../../../.build'",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"test": "jest",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/swr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
"scripts": {
"clean": "rimraf dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist && pnpm pack dist --pack-destination '../../../../.build'",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"test": "jest",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
"scripts": {
"clean": "rimraf dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist && pnpm pack dist --pack-destination '../../../../.build'",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"test": "jest",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/trpc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
},
"scripts": {
"clean": "rimraf dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist && pnpm pack dist --pack-destination '../../../../.build'",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"prepublishOnly": "pnpm build",
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
},
"scripts": {
"clean": "rimraf dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ../../LICENSE dist && copyfiles -u1 'res/**/*' dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ../../LICENSE dist && copyfiles -u1 'res/**/*' dist && pnpm pack dist --pack-destination '../../../.build'",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"prepublishOnly": "pnpm build",
Expand Down
3 changes: 1 addition & 2 deletions packages/schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"vscode:prepublish": "pnpm bundle",
"vscode:package": "vsce package --no-dependencies",
"clean": "rimraf bundle dist",
"build": "pnpm clean && pnpm lint && tsc && copyfiles -F \"bin/*\" dist && copyfiles ./README-global.md ./LICENSE ./package.json dist && renamer --replace \"README.md\" dist/README-global.md && copyfiles -u 1 \"src/res/*\" dist && node build/post-build.js",
"build": "pnpm clean && pnpm lint && tsc && copyfiles -F \"bin/*\" dist && copyfiles ./README-global.md ./LICENSE ./package.json dist && renamer --replace \"README.md\" dist/README-global.md && copyfiles -u 1 \"src/res/*\" dist && node build/post-build.js && pnpm pack dist --pack-destination '../../../.build'",
"bundle": "pnpm clean && pnpm lint && node build/bundle.js --minify",
"watch": "tsc --watch",
"lint": "eslint src tests --ext ts",
Expand Down Expand Up @@ -127,7 +127,6 @@
"@typescript-eslint/parser": "^5.42.0",
"@vscode/vsce": "^2.19.0",
"@zenstackhq/runtime": "workspace:*",
"@zenstackhq/testtools": "workspace:*",
"concurrently": "^7.4.0",
"copyfiles": "^2.4.1",
"dotenv": "^16.0.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/schema/src/plugins/plugin-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export function getDefaultOutputFolder() {
// Find the real runtime module path, it might be a symlink in pnpm
let runtimeModulePath = require.resolve('@zenstackhq/runtime');

if (process.env.NODE_ENV === 'test') {
if (process.env.ZENSTACK_TEST === '1') {
// handling the case when running as tests, resolve relative to CWD
runtimeModulePath = path.resolve(path.join(process.cwd(), 'node_modules', '@zenstackhq', 'runtime'));
}
Expand Down
35 changes: 29 additions & 6 deletions packages/schema/src/plugins/zod/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,9 @@ export default class Transformer {
if (isAggregateInputType(name)) {
name = `${name}Type`;
}
const end = `export const ${this.name}ObjectSchema = Schema`;
return `const Schema: z.ZodType<Omit<Prisma.${name}, ${AUXILIARY_FIELDS.map((f) => "'" + f + "'").join(
'|'
)}>> = ${schema};\n\n ${end}`;
return `export const ${this.name}ObjectSchema: z.ZodType<Omit<Prisma.${name}, ${AUXILIARY_FIELDS.map(
(f) => "'" + f + "'"
).join('|')}>> = ${schema};`;
}

addFinalWrappers({ zodStringFields }: { zodStringFields: string[] }) {
Expand Down Expand Up @@ -390,14 +389,21 @@ export default class Transformer {
const { selectImport, includeImport, selectZodSchemaLineLazy, includeZodSchemaLineLazy } =
this.resolveSelectIncludeImportAndZodSchemaLine(model);

let imports = [`import { z } from 'zod'`, selectImport, includeImport];
let imports = [
`import { z } from 'zod'`,
this.generateImportPrismaStatement(),
selectImport,
includeImport,
];
let codeBody = '';
const operations: [string, string][] = [];

if (findUnique) {
imports.push(
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`
);
codeBody += `findUnique: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema }),`;
operations.push(['findUnique', modelName]);
}

if (findFirst) {
Expand All @@ -412,6 +418,7 @@ export default class Transformer {
codeBody += `findFirst: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${upperCaseFirst(
modelName
)}ScalarFieldEnumSchema).optional() }),`;
operations.push(['findFirst', modelName]);
}

if (findMany) {
Expand All @@ -426,6 +433,7 @@ export default class Transformer {
codeBody += `findMany: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${upperCaseFirst(
modelName
)}ScalarFieldEnumSchema).optional() }),`;
operations.push(['findMany', modelName]);
}

if (createOne) {
Expand All @@ -434,27 +442,31 @@ export default class Transformer {
`import { ${modelName}UncheckedCreateInputObjectSchema } from '../objects/${modelName}UncheckedCreateInput.schema'`
);
codeBody += `create: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: z.union([${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema]) }),`;
operations.push(['create', modelName]);
}

if (createMany) {
imports.push(
`import { ${modelName}CreateManyInputObjectSchema } from '../objects/${modelName}CreateManyInput.schema'`
);
codeBody += `createMany: z.object({ data: z.union([${modelName}CreateManyInputObjectSchema, z.array(${modelName}CreateManyInputObjectSchema)]) }),`;
operations.push(['createMany', modelName]);
}

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

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

if (updateOne) {
Expand All @@ -464,6 +476,7 @@ export default class Transformer {
`import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`
);
codeBody += `update: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema]), where: ${modelName}WhereUniqueInputObjectSchema }),`;
operations.push(['update', modelName]);
}

if (updateMany) {
Expand All @@ -473,6 +486,7 @@ export default class Transformer {
`import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'`
);
codeBody += `updateMany: z.object({ data: z.union([${modelName}UpdateManyMutationInputObjectSchema, ${modelName}UncheckedUpdateManyInputObjectSchema]), where: ${modelName}WhereInputObjectSchema.optional() }),`;
operations.push(['updateMany', modelName]);
}

if (upsertOne) {
Expand All @@ -484,6 +498,7 @@ export default class Transformer {
`import { ${modelName}UncheckedUpdateInputObjectSchema } from '../objects/${modelName}UncheckedUpdateInput.schema'`
);
codeBody += `upsert: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema, create: z.union([${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema]), update: z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema]) }),`;
operations.push(['upsert', modelName]);
}

const aggregateOperations = [];
Expand Down Expand Up @@ -532,6 +547,7 @@ export default class Transformer {
codeBody += `aggregate: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), ${aggregateOperations.join(
', '
)} }),`;
operations.push(['aggregate', modelNameVar]);
}

if (groupBy) {
Expand All @@ -546,6 +562,7 @@ export default class Transformer {
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(${upperCaseFirst(
modelName
)}ScalarFieldEnumSchema), ${aggregateOperations.join(', ')} }),`;
operations.push(['groupBy', modelNameVar]);
}

imports = [...new Set(imports)];
Expand All @@ -555,7 +572,13 @@ export default class Transformer {
/* eslint-disable */
${imports.join(';\n')}
export const ${modelName}InputSchema = {
type ${modelName}InputSchemaType = {
${operations
.map((op) => indentString(`${op[0]}: z.ZodType<Prisma.${op[1]}${upperCaseFirst(op[0])}Args>`, 4))
.join(',\n')}
}
export const ${modelName}InputSchema: ${modelName}InputSchemaType = {
${indentString(codeBody, 4)}
};
`;
Expand Down
4 changes: 1 addition & 3 deletions packages/schema/src/utils/pkg-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ export function installPackage(
switch (manager) {
case 'yarn':
execSync(
`yarn --cwd "${projectPath}" add ${exactVersion ? '--exact' : ''} ${pkg}@${tag} ${
dev ? ' --dev' : ''
} --ignore-engines`
`yarn --cwd "${projectPath}" add ${exactVersion ? '--exact' : ''} ${pkg}@${tag} ${dev ? ' --dev' : ''}`
);
break;

Expand Down
Loading

0 comments on commit 51985b1

Please sign in to comment.