[TIL] 24.02.16

sssujijjl·2024년 2월 16일

[TIL]

목록 보기
36/51

[팀프로젝트 피드백]

  • 전체적으로 불필요한 주석은 삭제해주시면 좋을 것 같아요!

  • 추가적으로 try catch 에러핸들링이 안되어 있는 부분이 꽤 보이는데 외부 라이브러리를 많이 사용할수록 스스로 처리할 수 없는 에러는 꼭 핸들링이 필요합니다!!

  • 좋아요 생성에서 좋아요 취소기능까지 같이 하고 있는데 따로 api가 있어서 중복되니 하나는 없애는 게 좋을 것 같아요!

  • 좋아요 누른 게시물은 Like에서 where를 userId로 걸고 post를 join하면 한번에 가져올 수 있을 것 같아요!

추가적인 피드백들이 있지만 일단 내가 맡은 부분에 대한 피드백이 필요한 걸로 가져와봤다!

피드백 내용을 토대로 코드를 수정했다.

[코드]

router.get('/posts', jwtValidate, verifiedEmail, async (req, res, next) => {
  try {
    const user = res.locals.user;

    const like = await prisma.Likes.findMany({
      where: {
        userId: user.id,
      },
      select: {
        post: {
          select: {
            id: true,
        title: true,
        user: {
          select: {
            name: true,
          },
        },
        countlike: true,
        createdAt: true,
        view: true,
        attachFile: true,
          }
        }
      }
    });

    const posts = [];
    for (let i = 0; i < like.length; i++) {

      posts.push(like[i].post);

      if (like[i].post.attachFile !== null && like[i].post.attachFile !== '') {
        const tmp = like[i].post.attachFile
          .split(',')
          .filter((file) =>
            ['jpg', 'jpeg', 'png', 'gif'].includes(file.split('.')[1])
          );
        if (tmp.length === 0) {
          like[i].post.attachFile =
            'https://s3.orbi.kr/data/file/united2/ee9383d48d17470daf04007152b83dc0.png';
        } else {
          const command = new GetObjectCommand({
            Bucket: process.env.BUCKET_NAME,
            Key: tmp[0],
          });

          const signedUrl = await getSignedUrl(s3, command, { expiresIn: 3600 }); // 1h후 만료

          like[i].post.attachFile = signedUrl;
        }
      } else {
        like[i].post.attachFile =
          'https://s3.orbi.kr/data/file/united2/ee9383d48d17470daf04007152b83dc0.png';
      }
    }

    if (like.length < 1) {
      return res
        .status(404)
        .json({ message: '좋아요를 누른 게시물이 없습니다.' });
    }
    
    return res.status(200).render('main.ejs', { data: posts });

  } catch (error) {
    return res.status(500).send(`<script>alert('서버 내부에서 오류가 발생했습니다.');window.location.replace('/posts')</script>`);
  }
});

좋아요 누른 게시물을 불러오는 API이다.

  const likes = await prisma.Likes.findMany({
    where: {
      userId: user.id,
    },
  });

  let posts = await prisma.posts.findMany({
    where: {
      id: { in: likes.map((like) => like.postId) },
    },
    select: {
      id: true,
      title: true,
      user: {
        select: {
          name: true,
        },
      },
      countlike: true,
      createdAt: true,
      view: true,
      attachFile: true,
    },
  });

원래 코드는 이렇게 Likes 테이블과 posts 테이블을 불러와서 코드를 작성했는데

    const like = await prisma.Likes.findMany({
      where: {
        userId: user.id,
      },
      select: {
        post: {
          select: {
            id: true,
        title: true,
        user: {
          select: {
            name: true,
          },
        },
        countlike: true,
        createdAt: true,
        view: true,
        attachFile: true,
          }
        }
      }
    });

posts 테이블을 join해서 가져올 수 있도록 수정하였다!

그런데 원래는 post데이터를 내보내주었는데 like를 내보내주다보니
아래에 있는 attachFile 부분과 data를 내보내주는 부분을 변경하여야했다.

    const posts = [];
    for (let i = 0; i < like.length; i++) {

      posts.push(like[i].post);

      if (like[i].post.attachFile !== null && like[i].post.attachFile !== '') {
        const tmp = like[i].post.attachFile

이런 식으로 posts라는 변수에 빈 배열을 할당해준 후 like에서 post만 변수에 넣어주었다.

그리고 like.post.attachFile로 변경해주었다!!

[배운점]

튜터님의 피드백을 통해서 고쳐야할 부분이나 더 코드를 간결하게 작성하는 방법을 알 수 있었고,
피드백을 토대로 수정하면서 한번 더 공부도 되고 좋았다!

열심히 이 정도면 충분하다고 생각을 했어도 아직은 부족한 부분이 많은거 같다!

0개의 댓글