Skip to content

Commit

Permalink
Merge pull request #158 from BOOK-TALK/#127-enhance-hotopentalk
Browse files Browse the repository at this point in the history
#127 enhance hotopentalk
  • Loading branch information
chanwoo7 authored Sep 30, 2024
2 parents 2118fc3 + b644fb7 commit 2e83c2f
Show file tree
Hide file tree
Showing 7 changed files with 373 additions and 320 deletions.
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ dependencies {
// jwt
implementation 'io.jsonwebtoken:jjwt:0.9.1'

// flyway
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-mysql'

developmentOnly 'org.springframework.boot:spring-boot-devtools'

compileOnly 'org.projectlombok:lombok'
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/book/backend/domain/book/entity/Book.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ public class Book {

private String isbn;

private String bookname;

private String bookImageURL;

@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Opentalk opentalk;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.book.backend.domain.opentalk.controller;

import com.book.backend.domain.openapi.service.RequestValidate;
import com.book.backend.domain.opentalk.dto.OpentalkDto;
import com.book.backend.domain.opentalk.dto.OpentalkJoinResponseDto;
import com.book.backend.domain.opentalk.entity.Opentalk;
import com.book.backend.domain.opentalk.service.OpentalkService;
import com.book.backend.global.ResponseTemplate;
import com.book.backend.global.log.RequestLogger;
Expand All @@ -27,9 +29,10 @@
public class OpentalkController {
private final OpentalkService opentalkService;
private final ResponseTemplate responseTemplate;
private final RequestValidate requestValidate;

// 현재 핫한 오픈톡
@Operation(summary="현재 핫한 오픈톡", description="현재 핫한 오픈톡 top 3의 ID List를 반환합니다.",
@Operation(summary="현재 핫한 오픈톡", description="현재 핫한 오픈톡 top 5의 ID List를 반환합니다.",
responses = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = OpentalkDto.class)),
description = OpentalkDto.description)})
@GetMapping("/hot")
Expand All @@ -42,15 +45,15 @@ public ResponseEntity<?> getHotOpentalk() throws Exception {
}

// [오픈톡 참여하기]
@Operation(summary="오픈톡 참여하기", description="isbn, pageSize를 입력으로 받아 오픈톡 ID, 즐찾여부, 채팅 내역 반환",
parameters = {@Parameter(name = "isbn", description = "책 ISBN"), @Parameter(name = "pageSize", description = "페이지 당 개수")},
@Operation(summary="오픈톡 참여하기", description="isbn에 해당하는 오픈톡 DB ID, 즐찾여부 반환 & pageSize 만큼의 채팅 내역 반환 (bookname, bookImageURL은 새 오픈톡 생성시 필요한 값입니다.)",
parameters = {@Parameter(name = "isbn", description = "책 ISBN"), @Parameter(name = "bookname", description = "책 이름"), @Parameter(name = "bookImageURL", description = "책 이미지 url"), @Parameter(name = "pageSize", description = "채팅 개수")},
responses = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = OpentalkJoinResponseDto.class)),
description = OpentalkJoinResponseDto.description)})
@PostMapping("/join")
public ResponseEntity<?> joinOpentalk(@RequestParam String isbn, int pageSize) {
RequestLogger.param(new String[]{"isbn", "pageSize"}, isbn, pageSize);
OpentalkJoinResponseDto response = opentalkService.joinOpentalk(isbn, pageSize);

public ResponseEntity<?> joinOpentalk(@RequestParam String isbn, String bookname, @RequestParam(required = false) String bookImageURL, int pageSize) {
RequestLogger.param(new String[]{"isbn", "bookname", "bookImageURL", "pageSize"}, isbn, bookname, bookImageURL, pageSize);
requestValidate.isValidIsbn(isbn);
OpentalkJoinResponseDto response = opentalkService.joinOpentalk(isbn, bookname, bookImageURL, pageSize);
return responseTemplate.success(response, HttpStatus.OK);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class OpentalkService {
private final OpentalkResponseParser opentalkResponseParser;
private final MessageService messageService;

/* message 테이블에서 최근 200개 데이터 조회 -> opentalkId 기준으로 count 해서 가장 빈번하게 나오는 top 3 id 반환*/
/* message 테이블에서 최근 200개 데이터 조회 -> opentalkId 기준으로 count 해서 가장 빈번하게 나오는 top 5 id 반환*/
public List<Long> getHotOpentalkIds() {
log.trace("OpentalkService > hotOpentalk()");
List<Message> recent200Messages = messageRepository.findTop200ByOrderByCreatedAtDesc();
Expand All @@ -55,10 +55,10 @@ public List<Long> getHotOpentalkIds() {
Map<Long, Long> opentalkIdCountMap = recent200Messages.stream().collect(
Collectors.groupingBy(message -> message.getOpentalk().getOpentalkId(), Collectors.counting())
);
// value 순으로 정렬해서 top 3 id 반환
// value 순으로 정렬해서 top 5 id 반환
return opentalkIdCountMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(3)
.limit(5)
.map(Map.Entry::getKey)
.toList();
}
Expand Down Expand Up @@ -118,17 +118,21 @@ public List<Long> getFavoriteOpentalkIds() {
return opentalkIds;
}

// 해당 오픈톡 id 와 맵핑되는 책 isbn 을 찾아서 8번 open API 로 title, imageUrl 불러오기
// 해당 오픈톡 id의 bookname, bookImageURL 불러오기
public List<OpentalkDto> getBookInfo(List<Long> opentalkId) throws Exception {
log.trace("OpentalkService > getBookInfo()");
List<OpentalkDto> opentalkDtoList = new LinkedList<>();

for(Long id : opentalkId) {
OpentalkDto opentalkDto = OpentalkDto.builder().id(id).build();
// bookrepository 에서 opentalkid 로 찾기
Optional<Opentalk> opentalk = opentalkRepository.findByOpentalkId(id);
String isbn = opentalk.get().getBook().getIsbn();
DetailResponseDto detailResponseDto = detailService.detail(DetailRequestDto.builder().isbn13(isbn).build()); // 정보 가져오기
opentalkResponseParser.setSimpleBookInfo(opentalkDto, detailResponseDto); // detailResponseDto 에서 title 이랑 imageUrl 만 추출하기
Book book = opentalk.get().getBook();
OpentalkDto opentalkDto = OpentalkDto.builder()
.id(id)
.isbn13(book.getIsbn())
.bookName(book.getBookname())
.bookImageURL(book.getBookImageURL())
.build();
opentalkDtoList.add(opentalkDto);
}
return opentalkDtoList;
Expand All @@ -137,13 +141,14 @@ public List<OpentalkDto> getBookInfo(List<Long> opentalkId) throws Exception {

// 오픈톡 참여하기
@Transactional
public OpentalkJoinResponseDto joinOpentalk(String isbn, int pageSize){
public OpentalkJoinResponseDto joinOpentalk(String isbn, String bookname, String bookImageURL, int pageSize){
log.trace("OpentalkService > joinOpentalk()");
Opentalk opentalk = checkExistOpentalk(isbn);
if(opentalk == null){
opentalk = createOpentalkByIsbn(isbn);
opentalk = createOpentalkByIsbn(isbn, bookname, bookImageURL);
return OpentalkJoinResponseDto.builder().opentalkId(opentalk.getOpentalkId()).messageResponseDto(null).isFavorite(false).build();
}
// 오픈톡이 존재하는 경우
Pageable pageRequest = PageRequest.of(0, pageSize, Sort.by("createdAt").descending());
Page<Message> messagePage = messageService.getMessage(opentalk.getOpentalkId(), pageRequest);
List<MessageResponseDto> response = messageService.pageToDto(messagePage);
Expand All @@ -159,16 +164,19 @@ public OpentalkJoinResponseDto joinOpentalk(String isbn, int pageSize){
.build();
}


@Transactional
public Opentalk createOpentalkByIsbn(String isbn) {
log.trace("OpentalkService > createOpentalkByIsbn");// 새로운 오픈톡 생성
Book newBook = new Book();
newBook.setIsbn(isbn);
Book book = bookRepository.save(newBook);

Opentalk newOpentalk = new Opentalk();
newOpentalk.setBook(book);
return opentalkRepository.save(newOpentalk);
public Opentalk createOpentalkByIsbn(String isbn, String bookname, String bookImageURL) {
log.trace("OpentalkService > createOpentalkByIsbn");
Book book = new Book();
book.setIsbn(isbn);
book.setBookname(bookname);
book.setBookImageURL(bookImageURL);
bookRepository.save(book);

Opentalk opentalk = new Opentalk();
opentalk.setBook(book);
return opentalkRepository.save(opentalk);
}

public Opentalk checkExistOpentalk(String isbn) {
Expand Down
15 changes: 7 additions & 8 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
server:
port: 8080
address: 0.0.0.0
# ssl:
# key-store: readables.jks
# key-store-password: ${KEY_STORE_PASSWORD}
# key-store-type: JKS
# key-alias: 1

spring:
application:
Expand All @@ -19,21 +14,25 @@ spring:

jpa:
hibernate:
ddl-auto: update # entity 기반 스키마 생성 // update 로 변경

ddl-auto: validate # flyway 때문에 validate 으로 변경
properties:
hibernate:
globally_quoted_identifiers: true # sql 예약어와 일치하는 필드명 구분
format_sql: true
open-in-view: false
defer-datasource-initialization: true # ddl-auto 실행 후 data.sql 로 데이터 삽입
defer-datasource-initialization: false # ddl-auto 실행 후 data.sql 로 데이터 삽입
generate-ddl: false

sql: #data.sql 의 DDL 실행
init:
encoding: utf-8
mode: always
data-locations: classpath:sql/data.sql, classpath:sql/dummy.sql

flyway:
enabled: true
baseline-on-migrate: true

data:
redis:
host: ${REDIS_HOST}
Expand Down
37 changes: 37 additions & 0 deletions src/main/resources/db/migration/V2__Add_column_to_book.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
-- bookname 컬럼 추가
SET @col_exists_bookname = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'book' AND COLUMN_NAME = 'bookname'
);

SET @sql_bookname = IF(@col_exists_bookname = 0, 'ALTER TABLE book ADD COLUMN bookname VARCHAR(255);', 'SELECT "bookname column already exists";');
PREPARE stmt_bookname FROM @sql_bookname;
EXECUTE stmt_bookname;
DEALLOCATE PREPARE stmt_bookname;

-- book_imageurl 컬럼 추가
SET @col_exists_book_imageurl = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'book' AND COLUMN_NAME = 'book_imageurl'
);

SET @sql_book_imageurl = IF(@col_exists_book_imageurl = 0, 'ALTER TABLE book ADD COLUMN book_imageurl VARCHAR(255);', 'SELECT "book_imageurl column already exists";');
PREPARE stmt_book_imageurl FROM @sql_book_imageurl;
EXECUTE stmt_book_imageurl;
DEALLOCATE PREPARE stmt_book_imageurl;


/* 특정 테이블 칼럼 삭제
-- 1. 컬럼 존재 여부 확인
SELECT COUNT(*) INTO @col_exists
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'book' AND COLUMN_NAME = 'bookname';
-- 2. 컬럼 삭제
SET @sql = IF(@col_exists > 0, 'ALTER TABLE book DROP COLUMN bookname;', 'SELECT "Column does not exist";');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
*/
Loading

0 comments on commit 2e83c2f

Please sign in to comment.