Skip to content

API Generator: Add support for extending entities #3846

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 2 commits into from
May 13, 2025
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
5 changes: 5 additions & 0 deletions .changeset/small-islands-create.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@comet/api-generator": minor
---

Add basic support for inheritance used by entities
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { BaseEntity, defineConfig, Entity, MikroORM, PrimaryKey, Property } from "@mikro-orm/postgresql";
import { Field } from "@nestjs/graphql";
import { LazyMetadataStorage } from "@nestjs/graphql/dist/schema-builder/storages/lazy-metadata.storage";
import { v4 as uuid } from "uuid";

import { formatGeneratedFiles, parseSource } from "../../utils/test-helper";
import { generateCrud } from "../generate-crud";

@Entity({ abstract: true })
export abstract class TimestampEntity extends BaseEntity {
@Property({
columnType: "timestamp with time zone",
})
@Field()
createdAt: Date = new Date();

@Property({ onUpdate: () => new Date(), columnType: "timestamp with time zone" })
@Field()
updatedAt: Date = new Date();
}

@Entity()
export class TestEntityWithTimestamps extends TimestampEntity {
@PrimaryKey({ type: "uuid" })
id: string = uuid();

@Property()
foo: string;
}

describe("GenerateCrudInputExtendEntity", () => {
it("should include timestamp fields in the generated CRUD files", async () => {
LazyMetadataStorage.load();
const orm = await MikroORM.init(
defineConfig({
dbName: "test-db",
connect: false,
entities: [TestEntityWithTimestamps, TimestampEntity],
}),
);

const out = await generateCrud({ targetDirectory: __dirname }, orm.em.getMetadata().get("TestEntityWithTimestamps"));
const formattedOut = await formatGeneratedFiles(out);

const file = formattedOut.find((file) => file.name === "dto/test-entity-with-timestamps.filter.ts");
if (!file) throw new Error("File not found");

const source = parseSource(file.content);

const classes = source.getClasses();
expect(classes.length).toBe(1);

const cls = classes[0];
expect(cls.getName()).toBe("TestEntityWithTimestampsFilter");

const structure = cls.getStructure();
const properties = structure.properties || [];

const createdAtField = properties.find((prop) => prop.name === "createdAt");
const updatedAtField = properties.find((prop) => prop.name === "updatedAt");

expect(createdAtField).toBeDefined();
expect(createdAtField?.type).toBe("DateTimeFilter");

expect(updatedAtField).toBeDefined();
expect(updatedAtField?.type).toBe("DateTimeFilter");

orm.close();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@ function morphTsClass(metadata: EntityMetadata<any>) {
return tsClass;
}
export function morphTsProperty(name: string, metadata: EntityMetadata<any>) {
const tsClass = morphTsClass(metadata);
return tsClass.getPropertyOrThrow(name);
let currentClass: ClassDeclaration | undefined = morphTsClass(metadata);
while (currentClass) {
const prop = currentClass.getProperty(name);
if (prop) return prop;

currentClass = currentClass.getBaseClass();
}
throw new Error(`Property ${name} not found in ${metadata.className}`);
}

function findImportPath(importName: string, targetDirectory: string, metadata: EntityMetadata<any>) {
Expand Down