Entity validation

How do we validate fields that represent entities in our DTOs?

There are many ways to deal with this matter. Because of the way TypeORM naturally works, I'll use an approach that will save us the work of having to modify the service at all and allow us to leave it untouched, as the relationships will be automatically mapped for us when saving the entity. So, let's begin.

To validate an entity, the underlying rules must be followed

  • The entity must be an object

  • The object must have a single field, the id

  • The id must be a positive integer

Sounds familiar? We already have a structure that meets these requirements: The IdDto. Because of that, we can use it to type the categories field inside the DTO.

Apart from that, we just need to indicate that the validation used will be from the IdDto itself. We can achieve that with the @ValidateNested() decorator. Lastly, as it is not a primitive type, we need to explicitly state the type that is being validated with @Type(). With that, we should get the following result

@ArrayNotEmpty()
@ValidateNested()
@Type(() => IdDto)
readonly categories: IdDto[];

As a last improvement, we can create the decorator @IsEntity() for this specific validation. Let's do so now in common -> decorators -> is-entity.decorator.

/**
 * Checks if the value is an object with only a serial id.
 */
export const IsEntity = (): PropertyDecorator =>
  applyDecorators(
    ValidateNested(),
    Type(() => IdDto),
  );

Now, we can use it in this field and whenever necessary.

Commit - Implementing product logic and using nested validation

Last updated