Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
4ea6d0e
feat : 1,2단계 미션 제출
Nov 5, 2025
c713260
feat : 1,2단계 미션 제출 및 테스트 코드 수정
Nov 6, 2025
460e494
feat : is() 메소드를 위한 import문 추가
Nov 12, 2025
c97ea81
refactor : record 적용
Nov 12, 2025
d6c310c
feat : service 계층 생성
Nov 12, 2025
dcdb9f1
feat : 3단계 제출
Nov 13, 2025
a493121
feat : 4단계 제출
Nov 13, 2025
f9935e5
fix(dto) : local date, local time 으로 변경
Nov 16, 2025
08145b9
feat(repository) : 레포지토리 구현 및 계층 구현
Nov 16, 2025
b7fd4b7
Merge branch 'nonactress' into nonactress
nonactress Nov 16, 2025
b3d2c0b
fix : 개행 정리
Nov 16, 2025
1ea9e34
Merge branch 'nonactress' of https://github.com/nonactress/spring-roo…
Nov 16, 2025
2bc21d8
fix : 개행 정리
Nov 16, 2025
34ccc63
fix : DAO 사용 및 레포지토리 리팩토링
Nov 18, 2025
efff5e4
refactor : 레포지토리에 맞게 서비스 로직 리팩토링
Nov 18, 2025
00a0ae5
feat : 7단계 테스트
Nov 18, 2025
8c4503c
fix : post 중복 예외처리
Nov 18, 2025
043923b
feat : 스키마 멱등성 키 생성
Nov 18, 2025
034ede1
refactor : 멱등성 키를 위한 addReservation
Nov 18, 2025
f83d52e
refactor : dto 내부에서 엔티티로 변환 메소드 추가
Nov 18, 2025
b710148
refactor : Reservation 정적 팩토리 메소드 적용
Nov 18, 2025
88e93be
refactor : 헤더에 멱등성 키가 없어서 리팩토링
Nov 18, 2025
841ade6
fix : 개행 정리
Nov 18, 2025
2a5c805
refactor : 레포지토리를 서비스에 연결
Nov 19, 2025
20d0881
delete : 안쓰는 dto 삭제
Nov 19, 2025
b6887e0
refactor : localtime,date를 위한 dto 변환
Nov 19, 2025
675e113
refactor : localtime,date를 위한 레포지토리 변환
Nov 19, 2025
9934f11
refactor : localtime,date를 위한 어노테이션 변경(notBlank->notNull)
Nov 19, 2025
9b0add5
refactor : 개형정리
Nov 19, 2025
1422774
refactor : 개형정리2
Nov 19, 2025
d8f03be
refactor : LocalTime,LoaclDate로 변환
Nov 19, 2025
da52598
feat : READ.ME
Nov 19, 2025
ec7292a
feat : 실패 데이터 테스트 코드
Nov 23, 2025
242a374
feat : 성공 데이터 테스트 코드
Nov 23, 2025
568a051
feat : 멱등성 키 헤더에서 강요
Nov 23, 2025
3b5d63c
feat : simpleJdbcInsert 생성
Nov 25, 2025
457f630
feat : 예외 처리 패키지 생성
Nov 26, 2025
9834efd
feat : 동시성 문제 해결
Nov 26, 2025
5701129
feat : 개행정리
Nov 26, 2025
754903b
feat : 테스트 코드에 멱등성 키 헤더 추가
Nov 26, 2025
a271a5f
feat : 멱등성 키 중복 && body가 다른 경우 예외 처리 로직 생성
Nov 26, 2025
646800d
현재 작업 내용 저장
Nov 26, 2025
0c45865
충돌 해결 완료
Nov 26, 2025
1b9bc17
정리 제발!
Nov 26, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 16 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
### 컨트롤러 (Controller)
- `AdminController`: `@Controller`를 사용하여 웹 페이지를 반환합니다. 사용자가 특정 경로로 접속했을 때, 해당하는 HTML 파일을 렌더링하여 보여줍니다.
- `/`: `home.html` (홈 페이지)
- `/reservation`: `reservation.html` (예약 관리 페이지)
- `ReservationController`: `@RestController`를 사용하여 RESTful API를 제공합니다. HTTP 요청을 받아 `ReservationService`를 호출하고, 그 결과를 JSON 형태로 반환합니다.
- `GET /reservations`: 모든 예약 목록을 조회합니다.
- `POST /reservations`: 새로운 예약을 생성합니다.
- `DELETE /reservations/{id}`: 특정 예약을 삭제합니다.
## 📂 프로젝트 구조

### 서비스 (Service)
- `ReservationService`: 핵심 비즈니스 로직을 담당합니다.
- 예약 데이터를 `List<Reservation>` 형태로 메모리에 저장하고 관리합니다.
- `AtomicLong`을 사용하여 예약 ID를 순차적으로 생성합니다.
- 주요 메서드:
- `getAllReservations()`: 전체 예약 목록을 반환합니다.
- `addReservation()`: 새로운 예약을 리스트에 추가하고, 생성된 예약 객체를 반환합니다.
- `deleteReservation()`: ID를 기준으로 예약을 찾아 리스트에서 삭제합니다. 존재하지 않는 ID일 경우 `IllegalArgumentException`을 발생시킵니다.
```
.
├── build.gradle
├── src
│ ├── main
│ │ ├── java
│ │ │ └── roomescape
│ │ │ ├── controller
│ │ │ │ ├── AdminController.java # 웹 페이지 라우팅
│ │ │ │ └── ReservationController.java # 예약 API
│ │ │ ├── dto # 데이터 전송 객체
│ │ │ ├── model # 데이터 모델
│ │ │ ├── repository # 데이터 접근
│ │ │ └── service # 비즈니스 로직
```

## 📝 API 엔드포인트

Expand Down Expand Up @@ -44,8 +44,3 @@
"time": "14:00"
}
```

## 📄 페이지

- **홈**: `http://localhost:8080/`
- **예약 관리**: `http://localhost:8080/reservation`
10 changes: 10 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ repositories {

// 이 'dependencies' 블록 안에 모든 의존성을 관리하세요.
dependencies {
// [필수 1] JdbcTemplate을 포함한 스프링 JDBC 스타터
implementation 'org.springframework.boot:spring-boot-starter-jdbc'

// [필수 2] H2 데이터베이스 드라이버
runtimeOnly 'com.h2database:h2'

// [필수 1] 웹 서버 엔진
implementation 'org.springframework.boot:spring-boot-starter-web'

Expand All @@ -33,6 +39,10 @@ dependencies {
// 테스트에 필요한 의존성
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.rest-assured:rest-assured:5.3.1'


implementation 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'com.h2database:h2'
}

test {
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/roomescape/advice/ErrorCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package roomescape.advice;

import org.springframework.http.HttpStatus;

public enum ErrorCode {
// 1. 공통 에러
INVALID_INPUT_VALUE(HttpStatus.BAD_REQUEST, "COMMON-001", "잘못된 입력값입니다."),

// 2. 비즈니스 에러
DUPLICATE_DATA(HttpStatus.CONFLICT, "BIZ-001", "이미 처리된 요청이거나 중복된 데이터입니다."),
IDEMPOTENCY_KEY_MISMATCH(HttpStatus.BAD_REQUEST, "BIZ-002", "멱등성 키 불일치: 요청 내용이 다릅니다.");

private final HttpStatus httpStatus;
private final String code;
private final String message;

public HttpStatus getHttpStatus() {
return httpStatus;
}

public String getCode() {
return code;
}

public String getMessage() {
return message;
}

ErrorCode(HttpStatus httpStatus, String code, String message) {
this.httpStatus = httpStatus;
this.code = code;
this.message = message;
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

controller 폴더에 있는건 따로 의도하신바가 있으실까요??

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

의도한 바는 없습니다!!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그렇다면 적절한 위치는 어디가 좋을까요??

전역에서 발생하는 예외를 처리하는 공통 관심사이기 때문에, 컨트롤러 보다 좋은 위치가 있지 않을까 싶어요.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아아 제가 컨트롤러 폴더의 유무의 필요성에 대해 리뷰 남겨 주신 내용으로 잘못 이해한 것 같습니다.
GlobalExceptionHandler의 경우엔 당연히 controller 폴더에 있으면 안된다고 생각합니다.
Advice폴더를 생성하여 위치 시켜보도록 하겠습니다!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Advice 네이밍보다 좋은게 있을 것 같아요! 일반적인 케이스를 한번 찾아보면 더 도움이 될 것 같습니다~~

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package roomescape.controller;
package roomescape.controller; // (또는 roomescape.exception)

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package roomescape.advice;

public class IdempotencyKeyMismatchException extends RuntimeException {

private final ErrorCode errorCode;

public IdempotencyKeyMismatchException() {
super(ErrorCode.IDEMPOTENCY_KEY_MISMATCH.getMessage());
this.errorCode = ErrorCode.IDEMPOTENCY_KEY_MISMATCH;
}

public ErrorCode getErrorCode() {
return errorCode;
}
}

15 changes: 12 additions & 3 deletions src/main/java/roomescape/controller/ReservationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public ReservationController(ReservationService service) {

@GetMapping
public List<ReservationResponse> getAllReservations() {
return service.getAllReservations().stream()
return service.getAllReservations().stream()
.map(ReservationResponse::from) // (::from은 ReservationResponse::from과 동일)
.toList();
}
Expand All @@ -39,12 +39,21 @@ public ResponseEntity<Void> deleteReservation(@PathVariable Long id) {
@PostMapping
public ResponseEntity<ReservationResponse> createReservation(
@Valid @RequestBody ReservationCreateRequest requestDto
//@RequestHeader(value = "Idempotency-Key", required = true) String idempotencyKey
) {
/*if(service.exitsKey(idempotencyKey)) {
Reservation existingReservation = service.get(requestDto);
ReservationResponse responseDto = ReservationResponse.from(existingReservation);

Reservation reservationToCreate = requestDto.toEntity();
Reservation reservationToCreate = new Reservation(
requestDto.name(),
requestDto.date(),
requestDto.time()
);*/

Reservation savedReservation = service.addReservation(reservationToCreate);
//Reservation savedReservation = service.addReservation(reservationToCreate);

Reservation savedReservation = service.addReservation(requestDto.toEntity());
ReservationResponse responseDto = ReservationResponse.from(savedReservation);
URI location = URI.create("/reservations/" + savedReservation.getId());

Expand Down
21 changes: 21 additions & 0 deletions src/main/java/roomescape/dto/ErrorResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package roomescape.dto;

import org.springframework.http.ResponseEntity;
import roomescape.advice.ErrorCode;

public class ErrorResponse {
private final String code;
private final String message;

// 핵심: ErrorCode Enum만 던져주면 알아서 ResponseEntity를 만들어줌!
public static ResponseEntity<ErrorResponse> toResponseEntity(ErrorCode errorCode) {
return ResponseEntity
.status(errorCode.getHttpStatus())
.body(new ErrorResponse(errorCode.getCode(),errorCode.getMessage()));
}

public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
}
4 changes: 1 addition & 3 deletions src/main/java/roomescape/dto/ReservationCreateRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ public record ReservationCreateRequest(
LocalTime time
) {
public Reservation toEntity() {
return new Reservation(name, date, time);
return Reservation.create(name, date, time);
}
}


39 changes: 30 additions & 9 deletions src/main/java/roomescape/model/Reservation.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,45 @@
import java.time.LocalTime;

public class Reservation {
private Long id;
private String name;
Long id;
String name;
private LocalDate date;
private LocalTime time;

public Reservation(Long id, String name, LocalDate date, LocalTime time) {
private Reservation(Long id, String name, LocalDate date, LocalTime time) {
this.id = id;
this.name = name;
this.date = date;
this.time = time;
}

public Reservation(String name, LocalDate date, LocalTime time) {
this(null, name, date, time);
public static Reservation create(String name, LocalDate date, LocalTime time) {
return new Reservation(null, name, date, time);
}

public static Reservation of(Long id, String name, LocalDate date, LocalTime time) {
return new Reservation(id, name, date, time);
}

public Long getId() {
return id;
}

public String getName() {
return name;
}

public LocalDate getDate() {
return date;
}

public LocalTime getTime() {
return time;
}

public Long getId() { return id; }
public String getName() { return name; }
public LocalDate getDate() { return date; }
public LocalTime getTime() { return time; }
public Reservation(String name, LocalDate date, LocalTime time) {
this.name = name;
this.date = date;
this.time = time;
}
}
42 changes: 42 additions & 0 deletions src/main/java/roomescape/repository/IdempotencyRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package roomescape.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class IdempotencyRepository {
private final JdbcTemplate jdbcTemplate;

@Autowired
public IdempotencyRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public boolean exists(String key) {
String sql = "SELECT count(*) FROM idempotency_keys WHERE id = ?";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class, key);
return count != null && count > 0;
}

public void save(String key) {
String sql = "INSERT INTO idempotency_keys (id) VALUES (?)";
jdbcTemplate.update(sql, key);
}

public Long getReservationId(String key) {
try {
String sql = "SELECT reservation_id FROM idempotency_keys WHERE id = ?";
return jdbcTemplate.queryForObject(sql, Long.class, key);
} catch (EmptyResultDataAccessException e) {
return null;
}
}

public void save(String key, Long reservationId) {
String sql = "INSERT INTO idempotency_keys (id, reservation_id) VALUES (?, ?)";
jdbcTemplate.update(sql, key, reservationId);
}

}
Loading