1
votes

Say i have a Typeorm entity definition like this:

@Entity()
export class MyEntity {
  @PrimaryGeneratedColumn()
  id: number;

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

  ...

  @OneToOne(type => DocumentEntity)
  @JoinColumn()
  myDoc: DocumentEntity;

  @OneToMany(type => DocumentEntity, document => document.myEntity)
  @JoinColumn()
  otherDocs: DocumentEntity[];

  ...
}

so it has several entity relations, OneToMany/OneToOne

How do I approach this when crafting my DTOs?

Here I have an example DTO:

export class CreateMyEntityInputDto {

  @IsString()
  name: string;

  ...

  @IsOptional()
  myDoc: DocumentEntity;

  @IsOptional()
  otherDocs: DocumentEntity[];

  ....
}

I'm unclear on the best approach via Graphql

Current graphql interface:

####################
# @input
####################
input CreateDealInput {
  name: String
  ...
  myDoc: DocumentInput
  otherDocs: [DocumentInput]
} 

If I were designing a 'traditional' RESTful service, I would create my documents in the DB via a separate endpoint, wait for a success that returns documentID(s):int

then specify those ids as plain ints in the myEntity.myDoc / myEntity.otherDocs fields when creating a new myEntity (at a separate endpoint).

Do i take the same approach here? i.e. Do I create the documents entities in a separate query in graphql, parse out the created ids from the success response, then specify these int values in the DTO definition?

something like :

@IsOptional()
myDoc: int;

then, when creating the myEntity, load those (existing) document entities by id:int before finally saving via Typeorm?

Or do I pass all the document fields as nested entities in one big nested POST graphql query and use cascade to create them all?

1

1 Answers

1
votes

Just ran into the same issue myself. My solution was to reference the nested entity by id. In your example this would be something like:

export class CreateMyEntityInputDto {

  @IsString()
  name: string;

  ...

  @IsOptional()
  myDocId: string;

  @IsOptional()
  otherDocIds: string[];

  ....
}

Rather than create nested entities in one mutation, this solution requires multiple.