0

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

Patrick
  • 734
  • 11
  • 26
  • Does this answer your question? [Spring boot RequestBody with object fields that could be needed](https://stackoverflow.com/a/63625503/1553537). – Giorgi Tsiklauri Sep 03 '20 at 11:09

2 Answers2

3

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)
}
Lucas Campos
  • 1,860
  • 11
  • 17
1

I guess you can mark the variable as nullable with the ? operator. But I would suggest to use DTOs.

data class RegisterUserDto(
  val username: String,
  private val email: String,
  private val password: String
)
flaxel
  • 4,173
  • 4
  • 17
  • 30