Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
108 changes: 108 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Payper Server v2

## Policy
- 이미 작성되어 있는 기존 코드(사용자 또는 외부에서 작성된 것으로 보이는 코드)는 사용자의 허가나 직접적인 명령이 있기 전까지 수정하지 않는다.
- 기존 코드의 수정이 필요하다고 판단되는 경우, 반드시 사용자에게 먼저 확인을 받는다.

## Tech Stack
- **Framework**: Spring Boot 4.0.1 (Java 21)
- **ORM**: Spring Data JPA (Hibernate) + MySQL
- **Auth**: JWT (JJWT 0.12.6) + Kakao OAuth
- **Security**: Spring Security (Stateless, Bearer Token)
- **Build**: Gradle 9.2.1
Comment thread
khyun9807 marked this conversation as resolved.
- **Dev Tools**: Lombok

## Build & Run
```bash
./gradlew build # 빌드
./gradlew bootRun # 로컬 실행 (MySQL localhost:3306/payper_v2 필요)
./gradlew test # 테스트 실행
```

## Project Structure
```
com.payper.server
├── auth/ # 인증 (OAuth, JWT 발급/재발급/로그아웃)
│ ├── jwt/ # JWT 엔티티, 유틸리티, 리포지토리
│ └── util/ # OAuth 유틸리티 (Kakao)
├── comment/ # 댓글 도메인 (CRUD, 대댓글, 커서 페이지네이션)
├── post/ # 게시글 도메인 (CRUD, 오프셋 페이지네이션)
├── merchant/ # 가맹점 도메인
├── favorite/ # 즐겨찾기 도메인
├── user/ # 사용자 도메인
├── security/ # Spring Security 설정, JWT 필터
├── global/ # 공통 (BaseTimeEntity, ApiResponse, ErrorCode, 예외처리)
└── domain/test/ # 테스트 컨트롤러
```

## Package Convention (Feature-based)
```
[feature]/
├── controller/ # REST 엔드포인트
├── service/ # 비즈니스 로직 (@Service @Transactional)
├── repository/ # JPA Repository
├── entity/ # JPA 엔티티
└── dto/
├── request/ # 요청 DTO (@Valid)
└── response/ # 응답 DTO
```

## Key Patterns

### API Response
- 모든 응답은 `ApiResponse<T>` 래퍼 사용 (`global/response/ApiResponse.java`)
- 에러는 `ErrorCode` enum 기반 (`global/response/ErrorCode.java`)
- 예외는 `ApiException` 또는 `AuthException` 사용

### Entity
- `BaseTimeEntity` 상속으로 `createdAt`, `updatedAt` 자동 관리
- 엔티티 생성은 `static create()` 팩토리 메서드 사용
- 모든 연관관계는 `FetchType.LAZY` + 필요 시 `join fetch` JPQL

### Soft Delete
- Post, Comment에 적용: `isDeleted` + `deletedAt` 필드
- 게시글 삭제 시 댓글도 소프트 딜리트 (cascade)
- 삭제된 댓글은 자식이 있으면 "[삭제된 댓글입니다]"로 표시

### Pagination
- **게시글**: 오프셋 기반 (`Page<T>`, page/size 파라미터)
- **댓글**: 커서 기반 (`Slice<T>`, cursorId/size 파라미터)

### Auth Flow
1. 클라이언트 → `/auth/login` (oauthToken)
2. Kakao OAuth 검증 → User 조회/생성
3. Access Token (헤더) + Refresh Token (HttpOnly 쿠키) 발급
4. 인증 필요 API: `Authorization: Bearer <accessToken>`
5. 토큰 만료 시: `/auth/reissue` (쿠키의 refresh token 사용)

### Security
- 공개 API: GET `/api/v1/posts/**`, GET `/api/v1/comments/*/replies`, `/auth/**`
- 인증 필요: POST/PUT/DELETE `/api/v1/posts/**`, `/api/v1/comments/**`
- 관리자: `/admin/**`

### Validation
- 입력: Jakarta Bean Validation (`@NotBlank`, `@Size` 등)
- 비즈니스: 서비스 레이어에서 권한/상태 검증
- 에러 응답: `FieldErrorDto` 리스트 반환

### Transaction
- 서비스 클래스에 `@Transactional` 기본 적용
- 독립 트랜잭션 필요 시 `REQUIRES_NEW` 사용 (댓글 일괄 삭제, 리프레시 토큰 삭제)

## Main Entities
| Entity | 설명 | 특이사항 |
|--------|------|----------|
| User | 사용자 | UUID userIdentifier, soft deactivate (active 필드) |
| Post | 게시글 | soft delete, PostType(BENEFIT/QUESTION/ETC) |
| Comment | 댓글 | soft delete, 자기참조(대댓글), parentComment |
| Merchant | 가맹점 | Category와 연관 |
| Category | 카테고리 | 자기참조(계층 구조) |
| PostLike/PostBookmark/PostReport | 게시글 부가 | UK(post_id, user_id) |
| CommentLike | 댓글 좋아요 | UK(comment_id, user_id) |
| Favorite | 즐겨찾기 | UK(user_id, merchant_id) |
| RefreshTokenEntity | 리프레시 토큰 | 해시 저장, replay attack 방지 |

## Profiles
- **default (dev)**: localhost MySQL, ddl-auto: update, show-sql: true
- **prod**: 환경변수(DB_URL, DB_USERNAME, DB_PASSWORD), show-sql: false
- **test**: H2 인메모리, ddl-auto: create-drop
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.mysql:mysql-connector-j'

// swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.6'
Comment thread
khyun9807 marked this conversation as resolved.

// security
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt-api:0.12.6'
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/com/payper/server/auth/AuthApi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.payper.server.auth;

import com.payper.server.auth.dto.request.LoginRequest;
import com.payper.server.auth.dto.response.LoginSuccessResponse;
import com.payper.server.auth.dto.response.ReissueSuccessResponse;
import com.payper.server.global.response.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;

@Tag(name = "인증", description = "로그인, 토큰 재발급, 로그아웃 API")
public interface AuthApi {

@Operation(summary = "로그인", description = "OAuth 토큰으로 로그인 (미가입 시 자동 회원가입). Access Token은 응답 바디, Refresh Token은 HttpOnly 쿠키로 발급됩니다.", security = {})
ResponseEntity<ApiResponse<LoginSuccessResponse>> enroll(
LoginRequest loginRequest,
HttpServletResponse response
);

@Operation(summary = "토큰 재발급", description = "Refresh Token(쿠키)으로 새로운 Access Token을 발급합니다.", security = {})
ResponseEntity<ApiResponse<ReissueSuccessResponse>> reissue(
@Parameter(description = "Refresh Token (HttpOnly 쿠키로 자동 전송)") String refreshToken,
HttpServletResponse response
);

@Operation(summary = "로그아웃", description = "Refresh Token을 무효화하고 쿠키를 삭제합니다.", security = {})
ResponseEntity<ApiResponse<String>> logout(
@Parameter(description = "Refresh Token (HttpOnly 쿠키로 자동 전송)") String refreshToken,
HttpServletResponse response
);
}
2 changes: 1 addition & 1 deletion src/main/java/com/payper/server/auth/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
public class AuthController {
public class AuthController implements AuthApi {
private final AuthService authService;

@PostMapping("/login") //로그인 시도 -> 필요하면 가입 -> 로그인
Expand Down
13 changes: 0 additions & 13 deletions src/main/java/com/payper/server/auth/dto/request/JoinRequest.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.payper.server.auth.dto.request;


import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Schema(description = "로그인 요청")
public class LoginRequest {
@Schema(description = "OAuth Provider가 제공한 access token", example = "kakao_oauth_token_example")
@NotBlank(message="OAuth Provider가 제공한 oauth resource access token이 필요합니다.")
private String oauthToken;
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.payper.server.auth.dto.response;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@Schema(description = "로그인 성공 응답")
public class LoginSuccessResponse {
@Schema(description = "JWT Access Token", example = "eyJhbGciOiJIUzI1NiJ9...")
private String accessToken;
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.payper.server.auth.dto.response;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@Schema(description = "토큰 재발급 성공 응답")
public class ReissueSuccessResponse {
@Schema(description = "새로 발급된 JWT Access Token", example = "eyJhbGciOiJIUzI1NiJ9...")
private String accessToken;
}
45 changes: 45 additions & 0 deletions src/main/java/com/payper/server/comment/controller/CommentApi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.payper.server.comment.controller;

import com.payper.server.comment.dto.CommentRequest;
import com.payper.server.comment.dto.CommentResponse;
import com.payper.server.global.response.ApiResponse;
import com.payper.server.security.CustomUserDetails;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;

@Tag(name = "댓글", description = "댓글 수정/삭제, 내 댓글 조회, 대댓글 조회 API")
public interface CommentApi {

@Operation(summary = "댓글 수정", description = "작성자만 수정 가능")
@SecurityRequirement(name = "bearerAuth")
ResponseEntity<ApiResponse<Void>> updateComment(
CustomUserDetails user,
@Parameter(description = "댓글 ID", example = "1") Long commentId,
CommentRequest.UpdateComment request
);

@Operation(summary = "댓글 삭제", description = "작성자만 삭제 가능. 자식 댓글은 삭제되지 않습니다.")
@SecurityRequirement(name = "bearerAuth")
ResponseEntity<ApiResponse<Void>> deleteComment(
CustomUserDetails user,
@Parameter(description = "댓글 ID", example = "1") Long commentId
);

@Operation(summary = "내가 쓴 댓글 조회", description = "커서 기반 페이지네이션. 최신순 정렬. 삭제된 댓글은 제외됩니다.")
@SecurityRequirement(name = "bearerAuth")
ResponseEntity<ApiResponse<CommentResponse.MyCommentList>> getMyComments(
CustomUserDetails user,
@Parameter(description = "마지막 조회 댓글 ID (첫 요청 시 생략)") Long cursorId,
@Parameter(description = "조회 개수", example = "20") int size
);

@Operation(summary = "대댓글 조회", description = "부모 댓글의 대댓글을 커서 기반으로 조회합니다. 삭제된 댓글은 제외됩니다.", security = {})
ResponseEntity<ApiResponse<CommentResponse.CommentList>> getReplies(
@Parameter(description = "부모 댓글 ID", example = "1") Long parentId,
@Parameter(description = "마지막 조회 댓글 ID (첫 요청 시 생략)") Long cursorId,
@Parameter(description = "조회 개수", example = "20") int size
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
@RestController
@RequestMapping("/api/v1/comments")
@RequiredArgsConstructor
public class CommentController {
public class CommentController implements CommentApi {
private final CommentService commentService;

/**
Expand Down Expand Up @@ -48,9 +48,9 @@ public ResponseEntity<ApiResponse<Void>> deleteComment(

/**
* 내가 쓴 댓글 조회
*
*
* 무한 스크롤 방식
*
*
* 정렬: 최신 순
*/
@GetMapping("/me")
Expand All @@ -75,4 +75,4 @@ public ResponseEntity<ApiResponse<CommentResponse.CommentList>> getReplies(
CommentResponse.CommentList response = commentService.getReplies(parentId, cursorId, size);
return ResponseEntity.ok(ApiResponse.ok(response));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.payper.server.comment.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
Expand All @@ -9,21 +10,26 @@ public class CommentRequest {
/**
* 댓글 작성 DTO
*/
@Schema(description = "댓글 작성 요청")
public record CreateComment(
@Schema(description = "댓글 내용", example = "좋은 글이네요!")
@NotBlank(message = "댓글을 적어주세요.")
@Size(max = 21800, message = "댓글은 21,800자 이하여야 합니다.")
String content,

@Schema(description = "부모 댓글 ID (대댓글 작성 시)", example = "1", nullable = true)
@Nullable
Long parentCommentId
) {}

/**
* 댓글 수정 DTO
*/
@Schema(description = "댓글 수정 요청")
public record UpdateComment(
@Schema(description = "수정할 댓글 내용", example = "수정된 댓글입니다")
@NotBlank(message = "댓글을 적어주세요.")
@Size(max = 21800, message = "댓글은 21,800자 이하여야 합니다.")
String content
) {}
}
}
Loading