Sid
Sid

Reputation: 1014

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?

Upvotes: 1

Views: 111

Answers (2)

Sid
Sid

Reputation: 1014

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 {}) {

}

Upvotes: 1

Charles Semaan
Charles Semaan

Reputation: 273

This is only possible client side by using fragments https://www.apollographql.com/docs/react/data/fragments/

Perhaps you can use something like type inheritance perhaps by using this library https://github.com/nicolasdao/graphql-s2s

Check out this link for reference.

Upvotes: 0

Related Questions