혼자 고민해보기_ 개발/TIL (Today I Learned)

20230810(목)_ 트렐로 프로젝트 진행

nuri-story 2023. 8. 14. 11:44

금일 달성 항목

1) 프론트 구현 
2) 카드, 댓글 api 작성


문제 해결 과정 1 - 프론트 구현

[문제]

프론트에서 카드를 표현하거나, 보드를 get 해서 가져올때 프론트로 가져와야하는데 백단에서 api가 완성되어있지 않았습니다 ㅠ

 

[시도 및 해결]

동료분의 도움으로 /cards/:cardId로 조회하는 백엔드를 구현을 먼저 했습니다.

// 카드 단일 조회
CardRouter.get('/cards/:cardId', cardsController.getAllCard);
  // 카드 단일 조회
  getAllCard = async (req, res) => {
    try {
      const { cardId } = req.params;
      const findCard = await this.cardService.findAllCard(cardId);
      res.status(200).json({ findCard });
    } catch (err) {
      console.error(err.name, ':', err.message);
      return res.status(400).json({ massage: `${err.message}` });
    }
  };
  // 카드 단일 조회
  findAllCard = async (cardId) => {
    const findCard = await this.cardRepository.findAllCard(cardId);
    return findCard;
  };
  // 카드 단일 조회
  findAllCard = async (cardId) => {
    return await Card.findOne({
      where: { cardId },
      include: [
        {
          model: Column,
          include: [
            {
              model: Board,
            },
          ],
        },
      ],
    });
  };

 

 

 

프론트

const cardId = window.location.pathname.split('/')[2];

const taskName = document.querySelector('#taskName');
// console.log(taskName);
const taskColor = document.querySelector('#taskColor');
const taskStartDate = document.querySelector('#taskStartDate');
const taskDueDate = document.querySelector('#taskDueDate');
const taskDescription = document.querySelector('#taskDescription');
const selectUser = document.querySelector('.select-user');
let selectValue;
const inviteBut = document.querySelector('#inviteButton');

const getData = async () => {
  try {
    const response = await fetch(`/api/cards/${cardId}`);
    const { findCard } = await response.json();
    // console.log(findCard);
    const boardId = findCard.Column.Board.boardId;
    const { name, description, startDate, dueDate, color } = findCard;
    taskName.innerText = name; // 작업 이름
    taskDescription.innerText = description;
    taskStartDate.innerText = startDate;
    taskDueDate.innerText = dueDate;
    taskColor.style.backgroundColor = color;

    const inviteRes = await fetch(`/api/boards/${boardId}`);
    const { message } = await inviteRes.json();
    // console.log(message);
    const temp = message
      .map((data) => {
        return `
        <option value=${data.User.name}>${data.User.name}</option>
      `;
      })
      .join(' ');

    selectUser.innerHTML = temp;
    selectValue = message[0].User.name;
    // console.log(selectValue);
    const selectChange = () => {
      selectValue = selectUser.options[selectUser.selectedIndex].value;
    };
    selectUser.addEventListener('change', selectChange);
  } catch (error) {
    console.error('Error:', error);
  }
};
getData();

inviteBut.addEventListener('click', async (e) => {
  e.preventDefault();
  try {
    const response = await fetch(`/api/cards/${cardId}/share`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: selectValue,
      }),
    });
    const data = await response.json();
    console.log(data);
    if (data) {
      alert('초대가 되었습니다.');
    }
  } catch (error) {
    console.log(error);
  }
});

const commentContainer = document.querySelector('.comment-container');
// 댓글
const getComment = async () => {
  try {
    const response = await fetch(`/api/comment/${cardId}`);

    const { data } = await response.json();
    // console.log(data);
    const temp = data
      .map((data) => {
        return `
      <div class="border p-3 mb-3">
        <p>
          ${data.User.name}: ${data.comment}
          <a href="/comment-edit/${data.commentId}">수정</a>
          <button class="btn btn-link delete" data-id=${data.commentId}>삭제</button>
        </p>
      </div>
      `;
      })
      .join(' ');
    commentContainer.innerHTML = temp;
    commentContainer.addEventListener('click', async (e) => {
      if (e.target.classList.contains('delete')) {
        const commentId = e.target.getAttribute('data-id');
        // console.log(commentId);
        const response = await fetch(`/api/comments/${commentId}`, {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
        });
        const { data } = await response.json();
        if (data === '댓글을 삭제하였습니다.') window.location.reload();
      }
    });
  } catch (error) {
    console.error('Error:', error);
  }
};
getComment();

 

[알게된 점]

백엔드의 데이터를 통해 프론트에 뿌려주는 것이므로 명칭에 대한 고민과 구조를 더 단단히 해야겠다고 생각했습니다.