Tiny Star

🏕️내일배움캠프/📂Trello 만들기(23.08.07)

Trello 만들기 2일 _ 백엔드 코드 포스트맨 구동 확인 및 프론트엔드 제작

청크 2023. 8. 11. 11:28

스파르타 코딩클럽_내일 배움 캠프 spring 트랙 6기

[프로젝트] Trello 만들기

2023.08.07 ~ 2023.08.14

<프로젝트 정보>

개발도구 : IntelliJ

프로그래밍 언어 : Java

데이터베이스 : MySQL

프레임워크 : Spring

저장소 : GitHub

기타서비스 : Postman

 

 

<프로젝트 내용>

1일차에 완성한 백엔드 코드를 2일차 오전에 포스트맨에서 제대로 동작해서 DB에서 저장, 수정, 삭제가 되는지 확인했고, 문제가 없었다.

 

내가 맡은 기능이었던 칼럼(섹션)에 대한 서비스, 컨트롤러 코드

[SectionService]

package com.example.trello.service;

import com.example.trello.dto.SectionListResponseDto;
import com.example.trello.dto.SectionRequestDto;
import com.example.trello.dto.SectionResponseDto;
import com.example.trello.entity.Board;
import com.example.trello.entity.Section;
import com.example.trello.repository.SectionRepository;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class SectionService {

  private final SectionRepository sectionRepository;
  private final BoardService boardService;

  //컬럼 조회
  public SectionListResponseDto findBySectionWithCard() {
    List<SectionResponseDto> sectionList = sectionRepository.findAll().stream()
            .map(SectionResponseDto::new)
            .collect(Collectors.toList());

    return new SectionListResponseDto(sectionList);
  }

  //컬럼 생성
  public SectionResponseDto createSection(Long boardId, SectionRequestDto requestDto) {
    Board board = boardService.findBoard(boardId);
    Section section = sectionRepository.save(new Section(board, requestDto));
    return new SectionResponseDto(section);
  }

  //컬럼 이름 수정
  public SectionResponseDto updateSectionName(Long sectionId, SectionRequestDto requestDto) {
    Section section = sectionRepository.findById(sectionId).orElse(null);
    findSection(sectionId);
    if (section != null) {
      section.setSectionName(requestDto);
      sectionRepository.save(section);
      return new SectionResponseDto(section);
    }
    return new SectionResponseDto(section);
  }


  //컬럼 삭제
  public String sectionDelete(Long sectionId) {
    findSection(sectionId);
    sectionRepository.deleteById(sectionId);
    return "삭제가 완료되었습니다.";
  }


  public Section findSection(Long sectionId) {
    return sectionRepository.findById(sectionId).orElseThrow(() ->
            new IllegalArgumentException("해당 칼럼는 존재하지 않습니다."));
  }
}

[SectionController]

package com.example.trello.controller;

import com.example.trello.dto.SectionListResponseDto;
import com.example.trello.dto.SectionRequestDto;
import com.example.trello.dto.SectionResponseDto;
import com.example.trello.service.SectionService;
import java.util.concurrent.RejectedExecutionException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class SectionController {

  private final SectionService sectionService;

  //section 조회
  @GetMapping("/section")
  public ResponseEntity<SectionListResponseDto> findBySectionWithCard() {
    SectionListResponseDto result = sectionService.findBySectionWithCard();
    return ResponseEntity.ok().body(result);
  }

  //section 생성
  @PostMapping("/board/{boardId}/section")
  public ResponseEntity<SectionResponseDto> createSection(@PathVariable Long boardId,
                                                          @RequestBody SectionRequestDto sectionRequestDto) {
    SectionResponseDto createSection = sectionService.createSection(boardId, sectionRequestDto);
    return ResponseEntity.status(HttpStatus.CREATED).body(createSection);
  }

  //section 이름 수정
  @PutMapping("/section/{sectionId}")
  public ResponseEntity<SectionResponseDto> updateSectionName(@PathVariable Long sectionId,
                                                              @RequestBody SectionRequestDto requestDto) {
    try {
      SectionResponseDto result = sectionService.updateSectionName(sectionId, requestDto);
      return ResponseEntity.ok().body(result);
    } catch (RejectedExecutionException e) {
      return ResponseEntity.badRequest().build();
    }
  }

  //section 삭제
  @DeleteMapping("/section/{sectionId}")
  public ResponseEntity<String> sectionDelete(@PathVariable Long sectionId) {
    String message = sectionService.sectionDelete(sectionId);
    return ResponseEntity.ok(message);
  }

}

 

추가로 빠르게 백엔드를 완성한 뒤 작업한 회원가입 html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"
            integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
    <meta charset="UTF-8">
    <title>회원가입 페이지</title>
    <script src="signup.js"></script>
    <style>
        /* 전체 페이지를 가운데 정렬 */
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        /* 컨테이너 스타일 */
        .container {
            text-align: center;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin: auto;
            width: 300px;
            position: relative; /* 포지션 추가 */
        }

        /* 타이틀 스타일 */
        h1 {
            margin-bottom: 20px; /* 간격 추가 */
        }

        /* 회원가입 폼 스타일 */
        #signupForm {
            text-align: center;
            padding: 20px;
        }

        /* 입력 필드 스타일 */
        input[type="email"],
        input[type="password"],
        input[type="text"] {
            padding: 8px;
            margin-bottom: 10px;
            border-radius: 5px;
            width: 100%;
        }

        /* 버튼 스타일 */
        button[type="submit"] {
            background-color: black;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button[type="submit"]:hover {
            background-color: #333;
        }

    </style>

    <script>
        const host = 'http://' + window.location.host;


        function signup() {

            let email = $('#email').val();
            let password = $('#password').val();
            let nickname = $('#nickname').val();

            $.ajax({
                type: "POST",
                url: `/api/user/signup`,
                contentType: "application/json",
                data: JSON.stringify({
                    username: email,
                    password: password,
                    nickname: nickname
                }),
            })
                .done(function () {
                        alert('회원가입완료 !');
                        window.location.href = host + '/api/view/user/login';
                    }
                )
                .fail(function (xhr, textStatus, errorThrown) {
                    console.log('statusCode: ' + xhr.status);
                    console.log('뭔가 잘못되었습니다...');
                });
        }
    </script>
</head>
<body>
<div class="container">
    <h1>1보후퇴 2보전진</h1>
    <div id="signupForm">

        <input type="email" id="email" name="email" placeholder="이메일" required><br><br>

        <input type="password" id="password" name="password" placeholder="패스워드"required><br><br>

        <input type="text" id="nickname" name="nickname" placeholder="닉네임" required><br><br>

        <button type="submit" onclick="signup()">가입하기</button>
    </div>
</div>
</body>
</html>