'Java Reactive get ServerRequest body, run repository and return flux
I was trying to get the body of "users" in HttpRequest body from ServerRequest. I am using RouterFunction for this. This "users" key contains a list of users.
After that, I need to extract this list of users to get the Flux from a repository and return back to frontend. How can I achieve that?
@Repository
public interface UserRepository extends ReactiveCrudRepository<User, Integer> {
Flux<Account> findByUserIn(List userList);
}
How to modify the below code for it to work?
public Mono<ServerResponse> getUserList(ServerRequest request) {
Flux<User> users = request.bodyToMono(String.class).doOnSuccess(x -> {
JSONObject jObject = new JSONObject(x);
List userList= jObject.getJSONArray("users").toList();
userRepository.findByUserIn(userList);
})
return ServerResponse.ok().body(users, Repo.class);
}
Solution 1:[1]
I found the answer, stuck because of a few typos, and thanks to Toerktumlare pointing it out. I need to use flatMapMany.
public Mono<ServerResponse> getUserList(ServerRequest request) {
Flux<User> results = request.bodyToMono(String.class)
.flatMapMany(x -> {
JSONObject req = new JSONObject(x);
List userList = req.getJSONArray("users").toList();
return userRepository.findByUserIn(userList);
});
return ServerResponse.ok().body(results, User.class);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chee Conroy |
