Search code examples
javascriptnode.jsnestjsdto

is a good approach using public methods in dto?


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!


Solution

  • 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.