javascripttypescriptgraphqltypeormtypegraphql

How to use composition in Typegraphql


Im using typeorm and typegraphql to build an API and I would like to abstract out properties of an entity into separate files and then import them to clean up the file:

Example of current

@Entity()
@ObjectType()
export class Person extends BaseEntity {
  @Field()
  @Column()
  name: string;

  @Field()
  @Column()
  surname: string;

  @Field()
  @Column()
  age: number;

  @Field()
  @Column()
  email: string;
}

I would like to do something like this:


class Name {
  @Field()
  @Column()
  name: string;

  @Field()
  @Column()
  surname: string;
}
@Entity()
@ObjectType()
export class Person extends BaseEntity {
  @Field()
  @Column()
  age: number;

  @Field()
  @Column()
  email: string;

  // then import the class here 
  ...Name
}

Is there any way to do this without creating separate entities and tables?


Solution

  • Ended up using mixins to solve this because embedded entities doesn't work with both typeorm and typegraphql

    
    export const WithName = <SubClass extends Constructor>(subClass?: SubClass) => {
      @ObjectType({ isAbstract: true })
      @InputType({ isAbstract: true })
      class Mixin extends getFallbackClass(subClass) {
        constructor(...args: any[]) {
          super(...args);
        }
        @Field()
        @Column()
        first: string;
    
        @Field()
        @Column()
        second: string;
    
      }
    
      return Mixin;
    };
    
    

    then using it like:

    class Human extends WithName(class {}) {
    
    }