java - 在 Spring webflux 中处理条件响应的正确方法是什么
问题描述
我刚刚开始学习 Spring Web Flux。并且对于如何在反应式编程而不是命令式编程中完成工作有完全的改变或观点。
所以,我想实现一个非常简单的输出。
我有包含字段成功、消息和列表数据的响应类。
@Data
@Accessors(chain = true)
public class Response {
private boolean success;
private String message;
private List data;
}
和一个请求类
@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
- 如果找到用户,它可以给我用户类对象
- 现在我必须检查密码是否与 LoginRequest 中给出的密码匹配
所以我必须根据用户存储库更改响应,比如找不到用户
- 如果用户发现密码无效,我必须返回成功 = false 和消息 =“未找到用户”的响应
- 我必须返回成功 = false 和 message = "invalid password" 的响应,如果一切正常,那么
- 我必须返回 success = true 、 message = "Welcome" 和 List 以及用户名、电子邮件等。
我尝试了很多方法,但最后我未能实现这一目标。
解决方案
您不需要 Mono 作为控制器的参数,您可以接受来自 Spring 的标准数据绑定后的值。查看 Spring 文档以获取示例:https ://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-controller
你也不应该从你的 repo 中得到 null,如果找不到用户,你会得到一个空的 Mono(所以.map
,.filter
等不会被调用)。在这种情况下,您可以.switchIfEmpty
用作空检查的替代品。
如果您获得数据,您可以将其简单地.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())));
}
推荐阅读
- r - 在已排序的数据框列表中查找元素的平均位置
- r - 使用 geom_text_repel 自定义在行尾显示的标签
- javascript - 在正确的时间打印消息
- android - 评估项目应用时出现问题 - Firebase Analytics
- python - 如何找到离坐标点最近的networkx节点 - python
- typescript - 打字稿:在不丢失显式键的情况下强制执行对象值
- go - 创建 GORM 自定义数据类型,如何在扫描中获取上下文?
- julia - 增加 Plots.jl 中图例标签之间的间距/填充
- linux - /home/user 位于哪里?(/dev/sda1)
- javascript - 只有当参数为真时,我如何才能传递参数?