게시글 조회 API 응답값에서는 사용자 정보도 필요하기 때문에, 게시글 서비스가 사용할 사용자 정보 조회 API가 필요하다.
✅ 사용자 조회 API 만들기
user-service 프로젝트에서 아래 코드 작성하기
Response DTO 만들기
dto/UserResponseDto
public class UserResponseDto {
private Long userId;
private String email;
private String name;
public UserResponseDto(Long userId, String email, String name) {
this.userId = userId;
this.email = email;
this.name = name;
}
public Long getUserId() {
return userId;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
}
password는 노출되면 안 되는 정보이기 때문에 제외했다.
Service 로직 작성하기
service/UserService
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
...
public UserResponseDto getUser(Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다."));
return new UserResponseDto(
user.getUserId(),
user.getEmail(),
user.getName()
);
}
}
Controller 로직 작성하기
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
...
@GetMapping("{userId}")
public ResponseEntity<UserResponseDto> getUser(@PathVariable Long userId) {
UserResponseDto userResponseDto = userService.getUser(userId);
return ResponseEntity.ok(userResponseDto);
}
}