Skip to content

Commit

Permalink
Only import imports in schemas where imports is used (fix #113)
Browse files Browse the repository at this point in the history
  • Loading branch information
CarterGrimmeisen committed Jun 30, 2022
1 parent a33a475 commit f201dd7
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,24 @@ export const writeImportsForModel = (
]

if (config.imports) {
importList.push({
kind: StructureKind.ImportDeclaration,
namespaceImport: "imports",
moduleSpecifier: dotSlash(
path.relative(
outputPath,
path.resolve(path.dirname(schemaPath), config.imports),
const usesImports = model.fields.some(
(field) =>
field.documentation &&
/\s*@zod.*[^.\w]imports\.\w+\W/.test(field.documentation),
)

if (usesImports) {
importList.push({
kind: StructureKind.ImportDeclaration,
namespaceImport: "imports",
moduleSpecifier: dotSlash(
path.relative(
outputPath,
path.resolve(path.dirname(schemaPath), config.imports),
),
),
),
})
})
}
}

if (config.decimalJs && model.fields.some((f) => f.type === "Decimal")) {
Expand Down
53 changes: 53 additions & 0 deletions test/regressions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,57 @@ describe("Regression Tests", () => {

expect(config.imports).toBe(null)
})

test("#113", async () => {
const config = configSchema.parse({
imports: "./regressions.test",
})
const prismaOptions: PrismaOptions = {
outputPath: path.resolve(__dirname, "./prisma/zod"),
schemaPath: path.resolve(__dirname, "./prisma/schema.prisma"),
}

const {
datamodel: {
models: [userModel, postModel],
},
} = await getDMMF({
datamodel: `model User {
id String @id
type String
}
model Post {
id String @id
body String /// @zod.custom(imports.commentSchema)
}`,
})

const project = new Project()
const testFile = project.createSourceFile("test.ts")

writeImportsForModel(userModel, testFile, config, prismaOptions)

testFile.formatText({
indentSize: 2,
convertTabsToSpaces: true,
semicolons: SemicolonPreference.Remove,
})

expect(testFile.getFullText()).toBe('import * as z from "zod"\n')

testFile.removeText(0, testFile.getEnd())

writeImportsForModel(postModel, testFile, config, prismaOptions)

testFile.formatText({
indentSize: 2,
convertTabsToSpaces: true,
semicolons: SemicolonPreference.Remove,
})

expect(testFile.getFullText()).toBe(
'import * as z from "zod"\nimport * as imports from "../regressions.test"\n',
)
})
})

0 comments on commit f201dd7

Please sign in to comment.