diff --git a/src/code-generator/CodeFile.ts b/src/code-generator/CodeFile.ts index 0b5148d..07c7f70 100644 --- a/src/code-generator/CodeFile.ts +++ b/src/code-generator/CodeFile.ts @@ -45,7 +45,10 @@ export class CodeFile { const iw = new CodeWriter(); const tw = new CodeWriter(); + const selfName = path.basename(this.fileName, path.extname(this.fileName)); for (const [module, names] of Object.entries(this.imports)) { + const moduleName = path.basename(module, path.extname(module)); + if (module.startsWith("./") && moduleName === selfName) continue; iw.write(`import { ${[...names].join(", ")} } from "${module}";`); iw.write("\n"); } diff --git a/src/schema/schema-generator.test.ts b/src/schema/schema-generator.test.ts index d2286d5..1f17735 100644 --- a/src/schema/schema-generator.test.ts +++ b/src/schema/schema-generator.test.ts @@ -661,4 +661,37 @@ describe("schema generator tests", () => { expect(code).toMatch(/implements\s+Auditable\b/); expect(code).toMatch(/from "\.\/Auditable"/); }); + + it("should not emit self-imports for relations targeting the entity itself", () => { + const Category = defineEntity({ + name: "Category", + fields: [ + { + name: "name", + type: "String", + required: true, + }, + { + name: "parent", + type: "ManyToOne", + target: "Category", + }, + { + name: "children", + type: "OneToMany", + target: "Category", + mappedBy: "parent", + }, + ], + }); + + generateSchema(outDir, { schema: [Category] }); + const code = fs.readFileSync(path.join(outDir, "Category.ts"), { + encoding: "utf-8", + }); + + expect(code).not.toMatch(/from "\.\/Category"/); + expect(code).toMatch(/parent\?:\s*Relation/); + expect(code).toMatch(/children\?:\s*Relation\[\]/); + }); });