小编sdf*_*fsd的帖子

语句lambda可以用表达式lambda替换

我使用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

有人可以解释它是如何工作的以及它的全部内容?

java lambda spring spring-mvc optional

55
推荐指数
2
解决办法
3万
查看次数

在控制器或服务中验证?

我有一种在控制器中下载消息的方法

@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)

现在我的问题是应该在控制器还是服务中完成?我更喜欢在服务中这样做,但我不知道是否合适。

java spring spring-mvc spring-boot

1
推荐指数
2
解决办法
2156
查看次数

标签 统计

java ×2

spring ×2

spring-mvc ×2

lambda ×1

optional ×1

spring-boot ×1