Search code examples
spring-bootspring-restcontrolleraxon

(Spring boot) How can I ignore some field from request body inside rest controller


Suppose I have signUp method inside rest controller class looks like this.

  @PostMapping("/signup")
  fun authenticateSignUp(@RequestBody command: RegisterUserCommand): CompletableFuture<String> {
    return commandGateway.send<String>(command)
  }

So it requires request body which is RegisterUserCommand.

data class RegisterUserCommand(
  val userId: String,
  val balance: BigDecimal,
  val username: String,
  private val email: String,
  private val password: String
)

I want to ignore some fields like userId, balance so I can generate it later inside controller like this

@PostMapping("/signup")
fun authenticateSignUp(@RequestBody request: RegisterUserCommand): CompletableFuture<String> {
  val command = request.copy(userId = ObjectId.get().toHexString(), balance = BigDecimal.ZERO)
  return commandGateway.send<String>(command)
}

Are there any annotation to ignore this field so it won't return bad request even though I didn't put userId, balance within request body


Solution

  • As correctly pointed out by @flaxel, you can use ? from Kotlin and I believe add @JvmOverloads constructor to it as well.

    But, in my opinion, using DTO is the best way to deal with that for sure. The input of your Controller should not be the Command but just a DTO with the fields you are interested in. How you build your command with enhanced values should not be affected by it.

    In this case, you would have something like this (also added @TargetAggregateIdentifier because probably you missed it):

    data class RegisterUserCommand(
      @TargetAggregateIdentifier
      val userId: String,
      val balance: BigDecimal,
      val username: String,
      private val email: String,
      private val password: String
    )
    
    ...
    
    data class RegisterUserDto(
      val username: String,
      private val email: String,
      private val password: String
    )
    
    ...
    
    @PostMapping("/signup")
    fun authenticateSignUp(@RequestBody request: RegisterUserDto): CompletableFuture<String> {
      val command = new RegisterUserCommand // build the command the way you want it
      return commandGateway.send<String>(command)
    }