Joseph
Joseph

Reputation: 1091

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:

@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;

    // ...
@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

Upvotes: 6

Views: 2092

Answers (2)

elauser
elauser

Reputation: 106

I have the case where the Entities don't match the objects precisely. I have orders with products, but I only store the productId and resolve the product data fresh from a different system.

Here I think it makes more sense to separate the two for type safety. I don't get the real product {} object back, only the productId, but typescript thinks I have both there.

Upvotes: 2

smolinari
smolinari

Reputation: 701

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.

Upvotes: 6

Related Questions