繁体   English   中英

在 Spring webflux 中处理条件响应的正确方法是什么

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

我刚开始学习 spring web 助焊剂。 并且对于如何在反应式编程而不是命令式编程中完成工作有完全的改变或观点。

所以,我想实现一个非常简单的 output。

我有响应 class 字段成功,消息和列表数据。

@Data
@Accessors(chain = true)
public class Response {

    private boolean success;
    private String message;
    private List data;
}

和一个请求 class

@Data
@Accessors(chain = true)
public class LoginRequest {

    private String email;
    private String password;
}

我也有带有 webFlux 的 userRepository。

Mono<User> findUserByEmail(String email);

我有这样的登录操作。

@PostMapping("/login")
public Mono<Response> login(@RequestBody Mono<LoginRequest> request) {
}

现在我必须根据 userRepository 给我的内容返回响应。

  • 如果没有用户在场,它可能会返回 null
  • 如果找到用户,它可以给我用户 class object
  • 现在我必须检查密码是否与 LoginRequest 中给出的密码匹配

所以我必须根据用户存储库更改响应,比如找不到用户

  • 如果用户发现密码无效,我必须返回成功 = false 和消息 =“未找到用户”的响应
  • 我必须返回成功 = false 和 message = "invalid password" 的响应,如果一切正常,那么
  • 我必须返回success = true,message =“Welcome”,并列出用户名、email 等。

我尝试了很多方法,但最后我未能实现这一目标。

您不需要 Mono 作为 controller 的参数,您可以从 Spring 接受标准数据绑定后的值。 查看 Spring 文档以获取示例: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html

您也不应该从您的存储库中获取 null,如果找不到用户,您将得到一个空的.filter (所以.map ,不会被称为等) 在这种情况下,您可以使用.switchIfEmpty作为 null 检查的替代品。

如果您获得数据,您可以简单地.map为您需要的数据,因为您不需要阻止任何其他数据:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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