E
E
Eugenue Cesarevich2021-05-17 18:15:43
Java
Eugenue Cesarevich, 2021-05-17 18:15:43

How to make two methods per endpoint in a Spring REST controller?

I have several roles and one endpoint. Faced such a situation that each role needs its own set of parameters. Well, for example, there is a CONSUMER role and there is a PRODUCER role . And there is an endpoint that both roles have access to:

@PostMapping("/order")
public void pay(@RequestParam(value = "consumer-id") Integer consumerId,
                         @RequestParam(value = "consumer-region-code") Integer regionCode,
                         @AuthenticationPrincipal AuthorizedUser user) {
    ...
}

In fact, it would be sufficient for the user CONSUMER to have only the principal here. But for the PRODUCER user , only consumerIdand is needed regionCode, but the principal is not needed. Because of this, the method grows very much, each role brings something new. Ideally, it would be to make two separate methods on one endpoint:
@PostMapping("/order")
public void pay(@AuthenticationPrincipal AuthorizedUser user) {
    ...
}

@PostMapping("/order")
public void pay(@RequestParam(value = "consumer-id") Integer consumerId,
                         @RequestParam(value = "consumer-region-code") Integer regionCode) {
    ...
}

But then Spring will throw an error. How can I solve this problem with extra parameters and method overgrowth?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BorLaze, 2021-05-17
@cot_shaurma

Is this not it?

O
Orkhan, 2021-05-17
Hasanly @azerphoenix

Why not instead:

@PostMapping("/order")
public void pay(@AuthenticationPrincipal AuthorizedUser user) {
    ...
}

@PostMapping("/order")
public void pay(@RequestParam(value = "consumer-id") Integer consumerId,
                         @RequestParam(value = "consumer-region-code") Integer regionCode) {
    ...
}

do not use:
@PostMapping("/order")
public void pay(
@AuthenticationPrincipal AuthorizedUser user,
@RequestParam(value = "consumer-id", required = false) Integer consumerId,
@RequestParam(value = "consumer-region-code", required = false) Integer regionCode
) {
    ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question