Product

With the Product logic, there are also similarities with the lesson in the Core module, such as when copying the contents of the users' CreateDTO and Service, we should

  • In the CreateDTO, have the following

export class CreateProductDto {
  @Length(2, 50)
  readonly name: string;

  @IsOptional()
  @Length(1, 500)
  readonly description?: string;

  @IsCurrency()
  readonly price: number;

  @ArrayNotEmpty()
  @IsEntity()
  readonly categories: IdDto[];
}
  • In the Service, in findOne(), also fetch its categories

Now what's different: in the methods create() and update(), we should explicitly state what to do with the categories. In our case, we wish that, when a product is created, to associate it with existing categories. And when it's updated, that it receives a new set of relations. Due to this, in both methods, we shall first extract the categories from the DTO, and then...

In create(), associate the categories through the connect option.

data: {
  ...createProductDto,
  categories: { connect: categories },
},

And in update(), replace the associations with the set option.

categories: { set: categories },

Commit - Implementing product logic

Last updated