From fd11ba126b090785182064e725ed371824511d09 Mon Sep 17 00:00:00 2001 From: minisyu Date: Wed, 26 Jun 2024 21:20:24 +0900 Subject: [PATCH 1/3] =?UTF-8?q?refactor:=20=EC=82=AC=EC=9A=A9=EC=9E=90=20?= =?UTF-8?q?=EC=95=84=EC=9D=B4=EB=94=94=20=EC=A1=B0=ED=9A=8C=20=EB=A1=9C?= =?UTF-8?q?=EC=A7=81=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/emodi/emodi/controller/AuthController.java | 7 +++++-- .../com/emodi/emodi/service/dto/response/UserIdDto.java | 5 +++++ 2 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/emodi/emodi/service/dto/response/UserIdDto.java diff --git a/src/main/java/com/emodi/emodi/controller/AuthController.java b/src/main/java/com/emodi/emodi/controller/AuthController.java index ac7ddb9..4a29a07 100644 --- a/src/main/java/com/emodi/emodi/controller/AuthController.java +++ b/src/main/java/com/emodi/emodi/controller/AuthController.java @@ -14,6 +14,7 @@ import com.emodi.emodi.service.AuthService; import com.emodi.emodi.service.dto.SignupInfoRequest; import com.emodi.emodi.service.dto.request.LoginInfoRequest; +import com.emodi.emodi.service.dto.response.UserIdDto; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletResponse; @@ -47,7 +48,9 @@ public ResponseEntity login(@RequestBody LoginInfoRequest request, HttpS } @GetMapping("/me") - public Long getUserId(@CookieValue("jwt") String token) { - return jwtProvider.verifyToken(token); + public ResponseEntity getUserId(@CookieValue("jwt") String token) { + Long userId = jwtProvider.verifyToken(token); + return ResponseEntity.status(HttpStatus.OK) + .body(new UserIdDto(userId)); } } diff --git a/src/main/java/com/emodi/emodi/service/dto/response/UserIdDto.java b/src/main/java/com/emodi/emodi/service/dto/response/UserIdDto.java new file mode 100644 index 0000000..df96341 --- /dev/null +++ b/src/main/java/com/emodi/emodi/service/dto/response/UserIdDto.java @@ -0,0 +1,5 @@ +package com.emodi.emodi.service.dto.response; + +public record UserIdDto(Long userId) { + +} From 42e0fe90d94d60c9cc84162d84fd80ac62473d50 Mon Sep 17 00:00:00 2001 From: js l Date: Thu, 27 Jun 2024 21:11:27 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=EC=9E=84=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++ build.gradle | 3 ++ .../emodi/controller/DiaryController.java | 37 ++++++++++++++----- .../java/com/emodi/emodi/entity/Diary.java | 26 ++++++------- .../com/emodi/emodi/service/DiaryService.java | 25 ++++++++++--- src/main/resources/application.properties | 18 +++++++++ 6 files changed, 83 insertions(+), 29 deletions(-) diff --git a/.gitignore b/.gitignore index c2065bc..ace25e9 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,6 @@ out/ ### VS Code ### .vscode/ + + +.DS_Store diff --git a/build.gradle b/build.gradle index 4369268..1a7293e 100644 --- a/build.gradle +++ b/build.gradle @@ -39,6 +39,9 @@ dependencies { runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' // .env implementation 'me.paulschwarz:spring-dotenv:4.0.0' + + implementation 'com.h2database:h2' // 임베디드 데이터베이스 사용 시 + } tasks.named('test') { diff --git a/src/main/java/com/emodi/emodi/controller/DiaryController.java b/src/main/java/com/emodi/emodi/controller/DiaryController.java index d796e0d..d396db8 100644 --- a/src/main/java/com/emodi/emodi/controller/DiaryController.java +++ b/src/main/java/com/emodi/emodi/controller/DiaryController.java @@ -1,24 +1,23 @@ package com.emodi.emodi.controller; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; - import com.emodi.emodi.entity.Diary; import com.emodi.emodi.jwt.JwtProvider; import com.emodi.emodi.service.DiaryService; import com.emodi.emodi.service.dto.request.WriteDiaryRequest; import com.emodi.emodi.service.dto.response.WriteDiaryResponse; - +import lombok.Getter; import lombok.RequiredArgsConstructor; +import lombok.Setter; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; @Controller @RequiredArgsConstructor @RequestMapping("/api") +@Getter +@Setter public class DiaryController { private final DiaryService diaryService; private final JwtProvider jwtProvider; @@ -40,4 +39,24 @@ public ResponseEntity writeDiary( return ResponseEntity.status(HttpStatus.CREATED) .body(writeDiaryResponse); } + + + @PutMapping("/diaries/{diaryId}") + public ResponseEntity updateDiary( + @CookieValue("jwt") String token, + @PathVariable Long diaryId, + @RequestBody WriteDiaryRequest request + ) { + Long userId = jwtProvider.verifyToken(token); + + Diary diary = diaryService.updateDiary(diaryId, request); + + WriteDiaryResponse writeDiaryResponse = WriteDiaryResponse.toWriteDiaryResponse( + "일기 수정이 완료되었습니다.", + diary + ); + + return ResponseEntity.status(HttpStatus.OK) + .body(writeDiaryResponse); + } } diff --git a/src/main/java/com/emodi/emodi/entity/Diary.java b/src/main/java/com/emodi/emodi/entity/Diary.java index 64298a6..c47c064 100644 --- a/src/main/java/com/emodi/emodi/entity/Diary.java +++ b/src/main/java/com/emodi/emodi/entity/Diary.java @@ -1,28 +1,18 @@ package com.emodi.emodi.entity; -import java.time.LocalDate; - import com.emodi.emodi.entity.common.BaseTimeEntity; +import jakarta.persistence.*; +import lombok.*; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToOne; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; +import java.time.LocalDate; +import java.time.LocalDateTime; @Entity @Builder @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor @Getter +@Setter public class Diary extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -41,4 +31,10 @@ public class Diary extends BaseTimeEntity { @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "sentiment_id") private Sentiment sentiment; + + private LocalDateTime updatedAt; + + public void setUpdatedAt(LocalDateTime updatedAt) { + this.updatedAt = updatedAt; + } } diff --git a/src/main/java/com/emodi/emodi/service/DiaryService.java b/src/main/java/com/emodi/emodi/service/DiaryService.java index 2023eb4..789724e 100644 --- a/src/main/java/com/emodi/emodi/service/DiaryService.java +++ b/src/main/java/com/emodi/emodi/service/DiaryService.java @@ -1,16 +1,17 @@ package com.emodi.emodi.service; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - import com.emodi.emodi.entity.Diary; import com.emodi.emodi.entity.Sentiment; import com.emodi.emodi.entity.User; import com.emodi.emodi.repository.DiaryRepository; import com.emodi.emodi.repository.UserRepository; import com.emodi.emodi.service.dto.request.WriteDiaryRequest; - import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; @Service @Transactional @@ -22,13 +23,27 @@ public class DiaryService { public Diary writeDiary(Long userId, WriteDiaryRequest request) { User user = userRepository.findById(userId) - .orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다.")); + .orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다.")); Sentiment sentiment = sentimentService.analyze(request); Diary diary = request.toDiary(user, sentiment); return diaryRepository.save(diary); + } + + public Diary updateDiary(Long diaryId, WriteDiaryRequest request) { + Diary diary = diaryRepository.findById(diaryId) + .orElseThrow(() -> new IllegalArgumentException("일기를 찾을 수 없습니다.")); + + Sentiment sentiment = sentimentService.analyze(request); + + diary.setTitle(request.title()); + diary.setContent(request.content()); + diary.setDate(LocalDate.parse(request.date())); + diary.setSentiment(sentiment); + diary.setUpdatedAt(LocalDateTime.now()); + return diaryRepository.save(diary); } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 11a0a43..ca695cd 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1 +1,19 @@ spring.application.name=emodi + +# H2 ???? ?????? ?? +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=password +spring.h2.console.enabled=true + +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true + +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +# JWT ?? +jwt.secret-key=supersecretkey1234567890!@#$%^&*()_+ +jwt.expiration-time=3600000 From 60578b3ee114cca1f27d7ac824d9f1a86f5a799f Mon Sep 17 00:00:00 2001 From: js l Date: Thu, 27 Jun 2024 23:19:17 +0900 Subject: [PATCH 3/3] =?UTF-8?q?=EC=9D=BC=EA=B8=B0=20=EC=9E=91=EC=84=B1=20?= =?UTF-8?q?=EB=B0=8F=20=EC=88=98=EC=A0=95=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Diary 엔티티 클래스 수정: - @PrePersist와 @PreUpdate 메서드를 추가하여 엔티티가 저장되거나 업데이트되기 전에 updatedAt 필드를 자동으로 설정하도록 수정. - 이 변경 사항은 엔티티가 생성되거나 업데이트될 때마다 updatedAt 필드를 자동으로 갱신하여 데이터베이스와의 일관성을 유지하기 위함입니다. 2. DiaryService 클래스 수정: - writeDiary 메서드에서 updatedAt 필드를 설정하도록 추가. - 일기가 처음 작성될 때도 updatedAt 필드가 설정되어야 하므로, 이를 명시적으로 설정하도록 수정하였습니다. 3. DiaryController 클래스 수정: - 일기 작성 API 엔드포인트(/api/diaries) 구현. - 일기 수정 API 엔드포인트(/api/diaries/{diaryId}) 구현. - 사용자 요청에 따라 일기를 작성하고 수정할 수 있는 API 엔드포인트를 제공하여 사용자 인터페이스와의 상호작용을 지원합니다. 4. 테스트: - curl 명령어를 사용하여 일기 작성 및 수정 테스트 완료. - 일기 작성 시 일기가 정상적으로 저장되는 것을 확인. - 일기 수정 시 기존 일기가 정상적으로 업데이트되는 것을 확인. - 실제 API 호출을 통해 작성 및 수정 기능이 올바르게 동작하는지 검증하였습니다. 일기 작성 및 수정 기능이 정상적으로 동작함을 확인하였습니다. --- .../java/com/emodi/emodi/entity/Diary.java | 11 +++++++-- .../com/emodi/emodi/service/DiaryService.java | 1 + src/main/resources/application.properties | 23 ++++++++++--------- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/emodi/emodi/entity/Diary.java b/src/main/java/com/emodi/emodi/entity/Diary.java index c47c064..85479c6 100644 --- a/src/main/java/com/emodi/emodi/entity/Diary.java +++ b/src/main/java/com/emodi/emodi/entity/Diary.java @@ -32,9 +32,16 @@ public class Diary extends BaseTimeEntity { @JoinColumn(name = "sentiment_id") private Sentiment sentiment; + @Column(nullable = false) private LocalDateTime updatedAt; - public void setUpdatedAt(LocalDateTime updatedAt) { - this.updatedAt = updatedAt; + @PrePersist + public void prePersist() { + this.updatedAt = LocalDateTime.now(); + } + + @PreUpdate + public void preUpdate() { + this.updatedAt = LocalDateTime.now(); } } diff --git a/src/main/java/com/emodi/emodi/service/DiaryService.java b/src/main/java/com/emodi/emodi/service/DiaryService.java index 789724e..bf50a20 100644 --- a/src/main/java/com/emodi/emodi/service/DiaryService.java +++ b/src/main/java/com/emodi/emodi/service/DiaryService.java @@ -28,6 +28,7 @@ public Diary writeDiary(Long userId, WriteDiaryRequest request) { Sentiment sentiment = sentimentService.analyze(request); Diary diary = request.toDiary(user, sentiment); + diary.setUpdatedAt(LocalDateTime.now()); // Set updatedAt field return diaryRepository.save(diary); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ca695cd..baafa65 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,19 +1,20 @@ spring.application.name=emodi -# H2 ???? ?????? ?? -spring.datasource.url=jdbc:h2:mem:testdb -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password=password -spring.h2.console.enabled=true +# MySQL ?????? ?? +spring.datasource.url=jdbc:mysql://localhost:3306/test +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.datasource.username=root +spring.datasource.password=@220708 -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true -spring.h2.console.enabled=true -spring.h2.console.path=/h2-console - # JWT ?? -jwt.secret-key=supersecretkey1234567890!@#$%^&*()_+ +jwt.secret-key=dGhpc19pc19hX3N1cGVyX3NlY3JldF9rZXlfdGhhdF9pc18zMl9ieXRlc19sb25nIQ== jwt.expiration-time=3600000 + +# Sentiment API ?? +app.sentimentKey=mqqu0rvst7 +app.sentimentSecret=hqbOaHhe3oP6zecSC7GScKOIx4jImxtu1Yq395bJ +app.sentimentUrl=https://naveropenapi.apigw.ntruss.com/sentiment-analysis/v1/analyze