Spring Cloud - 12. Users Microservice 사용자 조회

목차

12. Users Microservice 사용자 조회

@Override
public UserDto getUserByUserId(String userId) {
UserEntity userEntity = userRepository.findByUserId(userId);

if (userEntity == null)
throw new UsernameNotFoundException("User not found");

UserDto userDto = new ModelMapper().map(userEntity, UserDto.class);

List<ResponseOrder> orders = new ArrayList<>();
userDto.setOrders(orders);

return userDto;
}

@Override
public Iterable<UserEntity> getUserByAll() {
return userRepository.findAll();
}
public interface UserRepository extends CrudRepository<UserEntity, Long> {

UserEntity findByUserId(String userId);
}

전체 User 정보 가져오기

@GetMapping("/users")
public ResponseEntity<List<ResponseUser>> getUsers() {
Iterable<UserEntity> userList = userService.getUserByAll();
List<ResponseUser> result = new ArrayList<>();

userList.forEach(v -> {
result.add(new ModelMapper().map(v, ResponseUser.class));
});

return ResponseEntity.status(HttpStatus.OK).body(result);
}

특정 User 정보 가져오기

@GetMapping("/users/{userId}")
public ResponseEntity<ResponseUser> getUsers(@PathVariable("userId") String userId) {
UserDto userDto = userService.getUserByUserId(userId);

ResponseUser returnValue = new ModelMapper().map(userDto, ResponseUser.class);

return ResponseEntity.status(HttpStatus.OK).body(returnValue);
}
Share