1

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?

2 Answers 2

1

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

}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Ended up using mixins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.