我使用Optional工具进行用户和邀请验证
@DeleteMapping("/friends/{username}")
public
HttpEntity<Boolean> removeFriend(
@ApiParam(value = "The user's name", required = true) @PathVariable String username
) {
Long fromId = authorizationService.getUserId();
return userService.findByUsername(username)
.map(user -> {
return friendshipService.findFriendship(fromId, user.getId())
.map(friendship -> {
friendshipService.removeFriendship(friendship);
friendship.setToId(friendship.getFromId());
friendship.setFromId(friendship.getToId());
friendshipService.removeFriendship(friendship);
return ResponseEntity.ok(true);
}).orElseGet(() -> ResponseEntity.notFound().build());
}).orElseThrow(() -> new ResourceNotFoundException("User not found"));
Run Code Online (Sandbox Code Playgroud)
但是,IntelliJ正在着色我的灰色返回 https://zapodaj.net/2f48b1a26c392.png.html 但是当我删除返回时,它向我突出显示没有返回https://zapodaj.net/37605f08165c9.png.html
有人可以解释它是如何工作的以及它的全部内容?
我有一种在控制器中下载消息的方法
@GetMapping(value = "/sent/{id}")
public
HttpEntity<MessageSent> getMessageSent(
@ApiParam(value = "The message ID", required = true) @PathVariable Long id
) {
return ResponseEntity.ok().body(messageSearchService.getMessageSent(id, authorizationService.getUserId()));
}
Run Code Online (Sandbox Code Playgroud)
但是,我忘记验证有关给定 ID 的消息是否属于用户。它在服务中也没有这样做。
@Override
public MessageSent getMessageSent(
@Min(1) Long messageId,
@Min(1) Long userId
) throws ResourceNotFoundException {
Optional<UserEntity> user = this.userRepository.findByIdAndEnabledTrue(userId);
user.orElseThrow(() -> new ResourceNotFoundException("No user found with id " + userId));
return this.messageRepository.findByIdAndSenderAndIsVisibleForSenderTrue(messageId, user.get())
.map(MessageEntity::getSentDTO)
.orElseThrow(() -> new ResourceNotFoundException("No message found with id " + messageId));
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是应该在控制器还是服务中完成?我更喜欢在服务中这样做,但我不知道是否合适。