skip to Main Content

I’m learning Nestjs and now I’m coding a simple API to manage customers, I made an endpoint to create a new customer and I have a class dto to check fields and some validations before inserting a new one. Is add some methods inside to class dto a good practice?

export class CreateCustomerDto {
  @IsString()
  @IsNotEmpty()
  name: string;
.
. More
. Fields
. Here
.
  public setLowercaseName() {
    return this.name.toLowerCase();
  }
}

Yes, I know I can add some decorator or transform to do the same thing, but It’s just an example of what I would like to do but I don’t know if it is a good practice working with class methods in dto…

Thanks!

2

Answers


  1. DTOs are simple objects that should not contain any business logic but may contain serialization and deserialization mechanisms for transferring data over the wire.

    In my opinion you can have public methods to do some operations on its data but make sure that the method is implementing a very specific operation related to only DTO and not something like this.name.toLowerCase(); because that is something common and should be defined as a helper.

    Login or Signup to reply.
  2. in my opinion, it is better to take it to the transformer and apply it here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search