I intend to write a process() method with project-reactor library
The process() method takes a byte array as a parameter and goes through the following steps. Assume all other methods for each step is written and ready to be used.
- deserialize the byte array to a Message object
- extract userID, userStatus and userAddress from the Message object
- retrieve a record by userId from the database
- update the record with userStatus and userAddress if these two value extracted from Message objects are not Null.
- save the record in the database
@Component
public class UserService {
@Autowired
private Repository repo;
//this is the method I want to fix
public Mono<User> process(byte[] byteArray) {
Message msg = deserialize(byteArray).block(); --> Question #1
String userId = extractUserId(msg);
String userStatus = extractUserStatus(msg);
String userAddress = extractUserAddress(msg);
return repo.find(userId)
.switchIfEmpty(Mono.defer(() -> {
log.error("Error Message");
return Mono.empty();
}))
.map(user -> {
if(userStatus != null) {
user.setStatus(userStatus);
}
if(userAddress != null) {
user.setAddress(userAddress);
}
})
.flatmap(repo::save);
}
private Mono<Message> deserialize(byte[] byteArray) {
//assume this method is written and is ready to be invoked;
}
private String extractUserId(Message msg) {
//assume this method is written and is ready to be invoked;
}
private String extractUserStatus(Message msg) {
//assume this method is written and is ready to be invoked;
}
private String extractUserAddress(Message msg) {
//assume this method is written and is ready to be invoked;
}
}
public class Repository {
public Mono<User> find (String id) {
//assume this method is written and is ready to be invoked;
}
public Mono<User> save(User user) {
//assume this method is written and is ready to be invoked;
}
}
Question 1: I am not supposed to block it, but I have to extractId from it for retrieving a record from the database and also use it later on for extracting userStatus and address.
Question 2: Should extractUserId, extractUserStatus and extractUserAddress methods return Mono?