I have just started learning spring web flux. and there is complete change or perspective of how to do the work in reactive programming instead of imperative programming.
So, i would like to achieve a very simple output.
I have response class with fields success, message and List data.
@Data
@Accessors(chain = true)
public class Response {
private boolean success;
private String message;
private List data;
}
and a Request class
@Data
@Accessors(chain = true)
public class LoginRequest {
private String email;
private String password;
}
I also have userRepository with webFlux.
Mono<User> findUserByEmail(String email);
and i have a login action like this.
@PostMapping("/login")
public Mono<Response> login(@RequestBody Mono<LoginRequest> request) {
}
Now i have to return response based on what userRepository gave me.
So I have to change response based on User repository like if user not found
I have tried lot of ways but at the end i failed to achieve this.
You don't need a Mono as your argument to your controller, you can accept the value after standard data binding from Spring. Check the Spring docs for examples: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-controller
You also shouldn't get null from your repo, if the user can't be found you'll get an empty Mono (so .map
, .filter
, etc won't be called). That being the case, you can use .switchIfEmpty
as replacement for null checking.
If you get data you can simply .map
it to what you need since you don't need to block for any other data:
public Mono<Response> login(LoginRequest request) {
return repo.findUserByEmail(request.getEmail())
.map(user ->
Objects.equals(request.getPassword(), user.getPassword())
? new Response(true, "Welcome", Collections.emptyList())//populate list here
: new Response(false, "invalid password", Collections.emptyList()))
//user wasn't found in the repo
.switchIfEmpty(Mono.just(new Response(false, "No user found", Collections.emptyList())));
}