Search code examples
typescriptgraphqlnestjsdrytypeorm

Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?


I'm creating a GraphQL API using NestJS and TypeORM. Starting with the classic User entity I've created both the user.type.ts and the user.entity.ts as described by the Nestjs documentation.

This is an example of the content:

  • user.entity.ts
@Entity({ schema: 'mydb', name: 'userList' })
export class User {

    @Column('varchar', { name: 'guid', unique: true, length: 36 })
    guid: string;

    @Column('varchar', { name: 'firstName', length: 50 })
    firstName: string;

    @Column('varchar', { name: 'lastName', length: 100 })
    lastName: string;

    // ...
  • user.type.ts
@ObjectType()
export class UserType {
  @Field({
    name: 'ID',
    description: 'Global Universal ID of the User',
  })
  guid: string;

  @Field()
  firstName: string;

  @Field()
  lastName: string;

  // ...

The question is: since they use the same fields, can I create a single class that combines the decorators of both classes?

For instance:

@Entity({ schema: 'mydb', name: 'userList' })
@ObjectType()
export class User {

    @Column('varchar', { name: 'guid', unique: true, length: 36 })
    @Field({
      name: 'ID',
      description: 'Global Universal ID of the User',
    })
    guid: string;

    @Field()
    @Column('varchar', { name: 'firstName', length: 50 })
    firstName: string;

    @Field()
    @Column('varchar', { name: 'lastName', length: 100 })
    lastName: string;

Is it an antipattern? are there any limitations or downsides in doing it?

Thanks in advance


Solution

  • You can do what you are proposing. It isn't a problem. And it is a personal preference to do so.

    However, you'll probably quickly learn as I have that despite the two having the same shape from a data structure perspective, the entity and the GraphQL object (or in NestJS terms, the Data Transfer Object or DTO) do have different purposes. You'll also find in some situations the need to convert from one to the other and to do so will require them to be separate.