[Practice] 게시판 API 만들기 (12)
2021. 4. 17. 12:32ㆍSpring/Practice
1. 문제
- 게시글에 대한 좋아요한 내용을 취소하는 API
2. 풀이
- BoardLikeRepository.java
package com.example.jpa.sample.board.repository;
import com.example.jpa.sample.board.entity.Board;
import com.example.jpa.sample.board.entity.BoardLike;
import com.example.jpa.sample.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface BoardLikeRepository extends JpaRepository<BoardLike, Long> {
long countByBoardAndUser(Board board, User user);
Optional<BoardLike> findByBoardAndUser(Board board, User user);
}
- BoardService.java
package com.example.jpa.sample.board.service;
import com.example.jpa.sample.board.entity.BoardType;
import com.example.jpa.sample.board.model.*;
import java.util.List;
public interface BoardService {
ServiceResult addBoard(BoardTypeInput boardTypeInput);
ServiceResult updateBoard(Long id, BoardTypeInput boardTypeInput);
ServiceResult deleteBoard(Long id);
List<BoardType> getAllBoardType();
ServiceResult setBoardTypeUsing(Long id, BoardTypeUsing boardTypeUsing);
List<BoardTypeCount> getBoardTypeCount();
ServiceResult setBoardTop(Long id, boolean topYn);
ServiceResult setBoardPeriod(Long id, BoardPeriod boardPeriod);
ServiceResult setBoardHits(Long id, String email);
ServiceResult setBoardLike(Long id, String email);
ServiceResult setBoardUnLike(Long id, String email);
}
- BoardServiceImpl.java
package com.example.jpa.sample.board.service;
import com.example.jpa.sample.board.entity.Board;
import com.example.jpa.sample.board.entity.BoardHits;
import com.example.jpa.sample.board.entity.BoardLike;
import com.example.jpa.sample.board.entity.BoardType;
import com.example.jpa.sample.board.model.*;
import com.example.jpa.sample.board.repository.*;
import com.example.jpa.sample.user.entity.User;
import com.example.jpa.sample.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@RequiredArgsConstructor
@Service
public class BoardServiceImpl implements BoardService {
private final BoardTypeRepository boardTypeRepository;
private final BoardRepository boardRepository;
private final BoardTypeCustomRepository boardTypeCustomRepository;
private final BoardHitsRepository boardHitsRepository;
private final BoardLikeRepository boardLikeRepository;
private final UserRepository userRepository;
@Override
public ServiceResult addBoard(BoardTypeInput boardTypeInput) {
BoardType boardType = boardTypeRepository.findByBoardName(boardTypeInput.getName());
if(boardType != null && boardTypeInput.getName().equals(boardType.getBoardName())) { // 동일한 게시판 제목이 있을 경우
return ServiceResult.fail("이미 동일한 게시판이 존재합니다.");
}
BoardType addBoardType = BoardType.builder()
.boardName(boardTypeInput.getName())
.regDate(LocalDateTime.now())
.build();
boardTypeRepository.save(addBoardType);
return ServiceResult.success();
}
@Override
public ServiceResult updateBoard(Long id, BoardTypeInput boardTypeInput) {
Optional<BoardType> optionalBoardType = boardTypeRepository.findById(id);
if(!optionalBoardType.isPresent()) {
return ServiceResult.fail("수정할 게시판 타입이 없습니다.");
}
BoardType boardType = optionalBoardType.get();
if(boardTypeInput.getName().equals(boardType.getBoardName())) { // 동일한 게시판 제목이 있을 경우
return ServiceResult.fail("수정할 이름이 동일한 게시판명 입니다.");
}
boardType.setBoardName(boardTypeInput.getName());
boardType.setUpdateDate(LocalDateTime.now());
boardTypeRepository.save(boardType);
return ServiceResult.success();
}
@Override
public ServiceResult deleteBoard(Long id) {
Optional<BoardType> optionalBoardType = boardTypeRepository.findById(id);
if(!optionalBoardType.isPresent()) {
return ServiceResult.fail("삭제할 게시판 타입이 없습니다.");
}
BoardType boardType = optionalBoardType.get();
if(boardRepository.countByBoardType(boardType) > 0) {
return ServiceResult.fail("삭제할 게시판 타입의 게시글이 존재합니다.");
}
boardTypeRepository.delete(boardType);
return ServiceResult.success();
}
@Override
public List<BoardType> getAllBoardType() {
return boardTypeRepository.findAll();
}
@Override
public ServiceResult setBoardTypeUsing(Long id, BoardTypeUsing boardTypeUsing) {
Optional<BoardType> optionalBoardType = boardTypeRepository.findById(id);
if(!optionalBoardType.isPresent()) {
return ServiceResult.fail("삭제할 게시판 타입이 없습니다.");
}
BoardType boardType = optionalBoardType.get();
boardType.setUsingYn(boardTypeUsing.isUsingYn());
boardTypeRepository.save(boardType);
return ServiceResult.success();
}
@Override
public List<BoardTypeCount> getBoardTypeCount() {
return boardTypeCustomRepository.getBoardTypeCount();
}
@Override
public ServiceResult setBoardTop(Long id, boolean topYn) {
Optional<Board> optionalBoard = boardRepository.findById(id);
if(!optionalBoard.isPresent()) {
return ServiceResult.fail("게시글이 존재하지 않습니다.");
}
Board board = optionalBoard.get();
if(board.isTopYn() == topYn) {
if(topYn) return ServiceResult.fail("이미 게시글이 최상단에 배체되어 있습니다.");
else return ServiceResult.fail("이미 게시글이 최상단에 해제되어 있습니다.");
}
board.setTopYn(topYn);
boardRepository.save(board);
return ServiceResult.success();
}
@Override
public ServiceResult setBoardPeriod(Long id, BoardPeriod boardPeriod) {
Optional<Board> optionalBoard = boardRepository.findById(id);
if(!optionalBoard.isPresent()) {
return ServiceResult.fail("게시글이 존재하지 않습니다.");
}
Board board = optionalBoard.get();
board.setPublishStartDate(boardPeriod.getStartDate());
board.setPublishEndDate(boardPeriod.getEndDate());
boardRepository.save(board);
return ServiceResult.success();
}
@Override
public ServiceResult setBoardHits(Long id, String email) {
Optional<Board> optionalBoard = boardRepository.findById(id);
if(!optionalBoard.isPresent()) {
return ServiceResult.fail("게시글이 존재하지 않습니다.");
}
Board board = optionalBoard.get();
Optional<User> optionalUser = userRepository.findByEmail(email);
if(!optionalUser.isPresent()) {
return ServiceResult.fail("회원 정보가 존재하지 않습니다.");
}
User user = optionalUser.get();
if(boardHitsRepository.countByBoardAndUser(board, user) > 0) {
return ServiceResult.fail("이미 조회수가 있습니다.");
}
boardHitsRepository.save(BoardHits.builder()
.board(board)
.user(user)
.regDate(LocalDateTime.now())
.build());
return ServiceResult.success();
}
@Override
public ServiceResult setBoardLike(Long id, String email) {
Optional<Board> optionalBoard = boardRepository.findById(id);
if(!optionalBoard.isPresent()) {
return ServiceResult.fail("게시글이 존재하지 않습니다.");
}
Board board = optionalBoard.get();
Optional<User> optionalUser = userRepository.findByEmail(email);
if(!optionalUser.isPresent()) {
return ServiceResult.fail("회원 정보가 존재하지 않습니다.");
}
User user = optionalUser.get();
long boardLikeCount = boardLikeRepository.countByBoardAndUser(board, user);
if(boardLikeCount > 0) {
return ServiceResult.fail("이미 좋아요한 내용이 있습니다.");
}
boardLikeRepository.save(BoardLike.builder()
.board(board)
.user(user)
.regDate(LocalDateTime.now())
.build());
return ServiceResult.success();
}
@Override
public ServiceResult setBoardUnLike(Long id, String email) {
Optional<Board> optionalBoard = boardRepository.findById(id);
if(!optionalBoard.isPresent()) {
return ServiceResult.fail("게시글이 존재하지 않습니다.");
}
Board board = optionalBoard.get();
Optional<User> optionalUser = userRepository.findByEmail(email);
if(!optionalUser.isPresent()) {
return ServiceResult.fail("회원 정보가 존재하지 않습니다.");
}
User user = optionalUser.get();
Optional<BoardLike> optionalBoardLike = boardLikeRepository.findByBoardAndUser(board, user);
if(!optionalBoardLike.isPresent()) {
return ServiceResult.fail("좋아요한 내용이 없습니다.");
}
BoardLike boardLike = optionalBoardLike.get();
boardLikeRepository.delete(boardLike);
return ServiceResult.success();
}
}
- ApiBoardController.java
package com.example.jpa.sample.board.controller;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.jpa.sample.board.entity.BoardType;
import com.example.jpa.sample.board.model.*;
import com.example.jpa.sample.board.service.BoardService;
import com.example.jpa.sample.common.model.ResponseResult;
import com.example.jpa.sample.notice.model.ResponseError;
import com.example.jpa.sample.user.model.ResponseMessage;
import com.example.jpa.sample.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RequiredArgsConstructor
@RestController
public class ApiBoardController {
private final BoardService boardService;
// 문제 1
@PostMapping("/api/board/type")
public ResponseEntity<?> addBoardType(@RequestBody @Valid BoardTypeInput boardTypeInput, Errors errors) {
if(errors.hasErrors()) {
List<ResponseError> responseErrorList = ResponseError.of(errors.getAllErrors());
return new ResponseEntity<>(ResponseMessage.fail("입력값이 정확하지 않습니다.", responseErrorList), HttpStatus.BAD_REQUEST);
}
ServiceResult result = boardService.addBoard(boardTypeInput);
if(!result.isResult()) {
return ResponseEntity.ok().body(ResponseMessage.fail(result.getMessage()));
}
return ResponseEntity.ok().build();
}
// 문제 2
@PutMapping("/api/board/type/{id}")
public ResponseEntity<?> updateBoardType(@PathVariable Long id, @RequestBody @Valid BoardTypeInput boardTypeInput, Errors errors) {
if(errors.hasErrors()) {
List<ResponseError> responseErrorList = ResponseError.of(errors.getAllErrors());
return new ResponseEntity<>(ResponseMessage.fail("입력값이 정확하지 않습니다.", responseErrorList), HttpStatus.BAD_REQUEST);
}
ServiceResult result = boardService.updateBoard(id, boardTypeInput);
if(!result.isResult()) {
return ResponseEntity.ok().body(ResponseMessage.fail(result.getMessage()));
}
return ResponseEntity.ok().build();
}
// 문제 3
@DeleteMapping("/api/board/type/{id}")
public ResponseEntity<?> deleteBoardType(@PathVariable Long id) {
ServiceResult result = boardService.deleteBoard(id);
if(!result.isResult()) {
return ResponseEntity.ok().body(ResponseMessage.fail(result.getMessage()));
}
return ResponseEntity.ok().body(ResponseMessage.success());
}
// 문제 4
@GetMapping("/api/board/type")
public ResponseEntity<?> boardType() {
List<BoardType> boardTypeList = boardService.getAllBoardType();
return ResponseEntity.ok().body(ResponseMessage.success(boardTypeList));
}
// 문제 5
@PatchMapping("/api/board/type/{id}/using")
public ResponseEntity<?> usingBoardType(@PathVariable Long id, @RequestBody BoardTypeUsing boardTypeUsing) {
ServiceResult result = boardService.setBoardTypeUsing(id, boardTypeUsing);
if(!result.isResult()) {
return ResponseEntity.ok().body(ResponseMessage.fail(result.getMessage()));
}
return ResponseEntity.ok().body(ResponseMessage.success());
}
// 문제 6
@GetMapping("/api/board/type/count")
public ResponseEntity<?> boardTypeCount() {
List<BoardTypeCount> boardTypeCountList = boardService.getBoardTypeCount();
return ResponseEntity.ok().body(boardTypeCountList);
}
// 문제 7
@PatchMapping("/api/board/{id}/top")
public ResponseEntity<?> boardPostTop(@PathVariable Long id) {
ServiceResult result = boardService.setBoardTop(id, true);
return ResponseEntity.ok().body(result);
}
// 문제 8
@PatchMapping("/api/board/{id}/top/clear")
public ResponseEntity<?> boardPostTopClear(@PathVariable Long id) {
ServiceResult result = boardService.setBoardTop(id, false);
return ResponseEntity.ok().body(result);
}
// 문제 9
@PatchMapping("/api/board/{id}/publish")
public ResponseEntity<?> boardPeriod(@PathVariable Long id, @RequestBody BoardPeriod boardPeriod) {
ServiceResult result = boardService.setBoardPeriod(id, boardPeriod);
if(!result.isResult()) {
return ResponseResult.fail(result.getMessage());
}
return ResponseResult.success();
}
// 문제 10
@PutMapping("/api/board/{id}/hits")
public ResponseEntity<?> boardHits(@PathVariable Long id, @RequestHeader("X-ACCESS-TOKEN") String token) {
String email = "";
try {
email = JwtUtils.getIssuer(token);
} catch(JWTVerificationException e) {
return ResponseResult.fail("토큰 정보가 정확하지 않습니다.");
}
ServiceResult result = boardService.setBoardHits(id, email);
if(result.isFail()) {
return ResponseResult.fail(result.getMessage());
}
return ResponseResult.success();
}
// 문제 11
@PutMapping("/api/board/{id}/like")
public ResponseEntity<?> boardLike(@PathVariable Long id, @RequestHeader("X-ACCESS-TOKEN") String token) {
String email = "";
try {
email = JwtUtils.getIssuer(token);
} catch(JWTVerificationException e) {
return ResponseResult.fail("토큰 정보가 정확하지 않습니다.");
}
ServiceResult result = boardService.setBoardLike(id, email);
return ResponseResult.result(result);
}
// 문제 12
@PutMapping("/api/board/{id}/unlike")
public ResponseEntity<?> boardUnLike(@PathVariable Long id, @RequestHeader("X-ACCESS-TOKEN") String token) {
String email = "";
try {
email = JwtUtils.getIssuer(token);
} catch(JWTVerificationException e) {
return ResponseResult.fail("토큰 정보가 정확하지 않습니다.");
}
ServiceResult result = boardService.setBoardUnLike(id, email);
return ResponseResult.result(result);
}
}
728x90
'Spring > Practice' 카테고리의 다른 글
[Practice] 게시판 API 만들기 (14) (0) | 2021.04.17 |
---|---|
[Practice] 게시판 API 만들기 (13) (0) | 2021.04.17 |
[Practice] 게시판 API 만들기 (11) (0) | 2021.04.17 |
[Practice] 게시판 API 만들기 (10) (0) | 2021.04.17 |