简体   繁体   中英

What is the proper way to deal with conditional response in Spring webflux

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.

  • It could return null if no user is present
  • It could give me User class object if user is found
  • now i have to check if password matches with the password given in LoginRequest

So I have to change response based on User repository like if user not found

  • I have to return response with success = false and message = "No user found" if user found with invalid password
  • I have to return response with success = false and message = "invalid password" and if everything is good then
  • I have to return success = true, message = "Welcome", and List with username,email etc.

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())));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM