-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2단계 - 경로 조회 기능 #10
Open
gmelon
wants to merge
9
commits into
next-step:gmelon
Choose a base branch
from
gmelon:step2
base: gmelon
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
2단계 - 경로 조회 기능 #10
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
488e063
Step2 요구사항 작성
gmelon 7860551
refactor: SectionService 부정형 조건문 개선
gmelon 53ebcd5
refactor: Station, Section 도메인이 직접 id를 비교하도록 개선
gmelon d103661
refactor: Section 도메인 생성자 체이닝 적용
gmelon 5e64bfa
test: 동일 객체의 필드끼리 비교할 때 usingRecursiveComparison() 사용하도록 개선
gmelon b0637c1
chore: 프로덕션, 테스트 profile 분리
gmelon a25da11
feat: 경로 조회 Controller, ResponseDto, 통합 테스트 작성
gmelon 5748df3
feat: 경로 조회 Service, 테스트 작성
gmelon 7c1e9db
feat: Section과 Station Controller에서 pathService를 호출하도록 수정, Path 통합테스트 수정
gmelon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
## 2단계 리팩토링 요구사항 | ||
- [x] SectionService 부정형 조건문 !(a || b) 형태로 바꾸기 | ||
- [x] Station에서 id를 꺼내 외부에서 비교하지 말고 직접 물어보기 | ||
- SectionService 개선 | ||
- [x] Section 도메인 생성자 체이닝 적용 | ||
- [x] test에서 필드끼리 비교할 때 usingRecursiveComparison() 사용해보기 | ||
- [x] LineDaoTest - hasSize(0) 을 isEmpty() 로 개선 | ||
|
||
## 2단계 기능 요구사항 | ||
- [x] 프로덕션, 테스트용 profile 다르게 설정하기 | ||
- 프로덕션 DB는 로컬에 저장, 테스트 DB는 인메모리로 동작하도록 설정 | ||
- [x] 경로 조회 API 구현 | ||
- 1. 최단 거리 경로, 2. 거리 정보, 3. 해당 거리에 대한 요금 응답 | ||
- 다른 노선으로의 환승도 고려해야 함 | ||
- Controller & Test 수정 | ||
- Section, Station Controller에서 PathService 로직 호출하도록 하기 | ||
- PathIntegrationTest 는 기존 데이터 없이 Section/Station Controller 호출만으로 데이터 구성해서 테스트하기 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package subway.application.path; | ||
|
||
import java.util.Arrays; | ||
|
||
public enum PathPrice { | ||
|
||
DEFAULT(0, 10, 1_250, 0), | ||
FIRST_STEP(10, 50, 1_250, 5), | ||
SECOND_STEP(50, Integer.MAX_VALUE, 2_050, 8); | ||
|
||
private final int distanceUnderLimit; | ||
private final int distanceUpperLimit; | ||
private final int defaultPrice; | ||
private final int billingUnit; | ||
|
||
PathPrice(int distanceUnderLimit, int distanceUpperLimit, int defaultPrice, int billingUnit) { | ||
this.distanceUnderLimit = distanceUnderLimit; | ||
this.distanceUpperLimit = distanceUpperLimit; | ||
this.defaultPrice = defaultPrice; | ||
this.billingUnit = billingUnit; | ||
} | ||
|
||
public static int calculate(int totalDistance) { | ||
PathPrice pathPrice = Arrays.stream(values()) | ||
.filter(value -> totalDistance <= value.distanceUpperLimit) | ||
.findFirst() | ||
.orElseThrow(() -> new IllegalArgumentException("경로의 전체 거리 값이 잘못되었습니다.")); | ||
|
||
return pathPrice.defaultPrice | ||
+ calculateOverPrice(totalDistance - pathPrice.distanceUnderLimit,pathPrice.billingUnit); | ||
} | ||
|
||
private static int calculateOverPrice(int distance, int billingUnit) { | ||
if (billingUnit == 0) { | ||
return 0; | ||
} | ||
return 100 * ((distance - 1) / billingUnit + 1); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
package subway.application.path; | ||
|
||
import org.jgrapht.GraphPath; | ||
import org.jgrapht.alg.shortestpath.DijkstraShortestPath; | ||
import org.jgrapht.graph.DefaultWeightedEdge; | ||
import org.jgrapht.graph.WeightedPseudograph; | ||
import org.springframework.stereotype.Service; | ||
import subway.dao.SectionDao; | ||
import subway.dao.StationDao; | ||
import subway.domain.Section; | ||
import subway.domain.Station; | ||
import subway.dto.PathResponse; | ||
import subway.dto.StationResponse; | ||
|
||
import javax.annotation.PostConstruct; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
|
||
@Service | ||
public class PathService { | ||
|
||
static final WeightedPseudograph<Long, DefaultWeightedEdge> GRAPH = new WeightedPseudograph<>(DefaultWeightedEdge.class); | ||
|
||
private final StationDao stationDao; | ||
private final SectionDao sectionDao; | ||
|
||
public PathService(StationDao stationDao, SectionDao sectionDao) { | ||
this.stationDao = stationDao; | ||
this.sectionDao = sectionDao; | ||
} | ||
|
||
@PostConstruct | ||
void addExistingDataToGraph() { | ||
List<Station> stations = stationDao.findAll(); | ||
for (Station station : stations) { | ||
addVertex(station.getId()); | ||
} | ||
|
||
List<Section> sections = sectionDao.findAll(); | ||
for (Section section : sections) { | ||
addEdge(section.getUpStation().getId(), section.getDownStation().getId(), section.getDistance()); | ||
} | ||
} | ||
|
||
public PathResponse findShortestPath(Long departureStationId, Long arrivalStationId) { | ||
validateStationsAreNotSame(departureStationId, arrivalStationId); | ||
|
||
GraphPath<Long, DefaultWeightedEdge> path = getPath(departureStationId, arrivalStationId); | ||
List<StationResponse> stationResponses = path.getVertexList().stream() | ||
.map(stationId -> stationDao.findById(stationId) | ||
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 Station 입니다."))) | ||
.map(StationResponse::of) | ||
.collect(Collectors.toList()); | ||
int totalDistance = (int) path.getWeight(); | ||
|
||
return new PathResponse(stationResponses, totalDistance, PathPrice.calculate(totalDistance)); | ||
} | ||
|
||
private void validateStationsAreNotSame(Long departureStationId, Long arrivalStationId) { | ||
if (departureStationId.equals(arrivalStationId)) { | ||
throw new IllegalArgumentException("출발역과 도착역이 동일합니다."); | ||
} | ||
} | ||
|
||
private GraphPath<Long, DefaultWeightedEdge> getPath(Long departureStationId, Long arrivalStationId) { | ||
DijkstraShortestPath<Long, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(GRAPH); | ||
|
||
GraphPath<Long, DefaultWeightedEdge> path; | ||
try { | ||
path = dijkstra.getPath(departureStationId, arrivalStationId); | ||
} catch (IllegalArgumentException exception) { | ||
throw new IllegalArgumentException("출발역 또는 도착역이 존재하지 않습니다."); | ||
} | ||
|
||
if (path == null) { | ||
throw new IllegalArgumentException("출발역과 도착역 사이에 경로가 존재하지 않습니다."); | ||
} | ||
|
||
return path; | ||
} | ||
|
||
public void addVertex(Long vertex) { | ||
GRAPH.addVertex(vertex); | ||
} | ||
|
||
public void removeVertex(Long vertex) { | ||
GRAPH.removeVertex(vertex); | ||
} | ||
|
||
public void addEdge(Long startVertex, Long endVertex, int weight) { | ||
GRAPH.setEdgeWeight(GRAPH.addEdge(startVertex, endVertex), weight); | ||
} | ||
|
||
public void removeEdge(Long startVertex, Long endVertex) { | ||
GRAPH.removeEdge(startVertex, endVertex); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package subway.dto; | ||
|
||
import java.util.List; | ||
|
||
public class PathResponse { | ||
private List<StationResponse> path; | ||
private int totalDistance; | ||
private int price; | ||
|
||
public PathResponse(List<StationResponse> path, int totalDistance, int price) { | ||
this.path = path; | ||
this.totalDistance = totalDistance; | ||
this.price = price; | ||
} | ||
|
||
public List<StationResponse> getPath() { | ||
return path; | ||
} | ||
|
||
public int getTotalDistance() { | ||
return totalDistance; | ||
} | ||
|
||
public int getPrice() { | ||
return price; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package subway.ui; | ||
|
||
import org.springframework.web.bind.annotation.GetMapping; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RequestParam; | ||
import org.springframework.web.bind.annotation.RestController; | ||
import subway.application.path.PathService; | ||
import subway.dto.PathResponse; | ||
|
||
@RestController | ||
@RequestMapping("/path") | ||
public class PathController { | ||
|
||
private final PathService pathService; | ||
|
||
public PathController(PathService pathService) { | ||
this.pathService = pathService; | ||
} | ||
|
||
@GetMapping | ||
public PathResponse findShortestPath(@RequestParam Long departureStationId, @RequestParam Long arrivalStationId) { | ||
return pathService.findShortestPath(departureStationId, arrivalStationId); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
spring.h2.console.enabled=true | ||
|
||
spring.datasource.url=jdbc:h2:mem:subway;MODE=MySQL | ||
spring.datasource.url=jdbc:h2:~/subway;MODE=MySQL | ||
spring.datasource.driver-class-name=org.h2.Driver | ||
|
||
spring.sql.init.mode=always |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Section, Station Controller에서 PathService의 로직을 호출하는데 이에 대한 검증을 PathController 통합 테스트에서만 진행해도 괜찮을까요?? 아니면 Section과 Station 통합 테스트에서도 어떻게든 검증을 하는게 좋을까요??
통합 테스트 이기 때문에 Path 통합 테스트에서 Section/Station API를 호출하고 제대로된 경로 정보를 반환하는지 확인하는게 더 적절한가 싶기도 하고 고민이 되네요🥲🥲