Home > Net >  question about using DTO of a service layer argument
question about using DTO of a service layer argument

Time:07-10

I have a question about which service layer.

// 1
export class SomeService{
  async create(dto:CreateSomeDto) {}
}

or

// 2 
export class SomeService{
  async create(title: string, content: string) {}
}

It seems that many people are using the same as 1.

However, I was confused by the article that this increases interdependence between the controller and the service layer.

They say that the controller layer should depend unidirectionally on the service layer.

I know there is no right answer, but please tell me clarify the pros and cons of each?

CodePudding user response:

There are no pros using method 1 except that it saves you very little time of defining probably same DTO type definitions again for service's method. however the trade off does not worth it and I suggest using method 2 instead.

Because when your app grows, there will be situations where services methods will be called from another service/controller. That said, any other service's callers may have to provide extra parameters which not even used in service's method in order to be able to call it.

For example suppose you have a UsersService and UsersController to verify user's phone number and sign him up:

class UsersController() {
  @Post('register')
  register(@Body() dto: RegisterUserDto) {
    const isVerified = this.verificationService.verify(dto.code);
    if (isVerified) {
      return this.usersService.create(dto);
    }
  }
}

class UsersService() {
  create(dto: RegisterUserDto) {
    // create user... 
  }
}

It works fine however a few months later your client requests a feature to add users manually from its dashboard. since you've already implemented UsersService.create method, you can use it from AdminController directly however because UsersService.create parameter requires an code parameter, The compiler does not allow you to call the method without it even though code property is not used in UsersService.create.

  • Related