Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

채채

[3주차] 댓글 기능 관련 API 제작 본문

dev-log/web_study

[3주차] 댓글 기능 관련 API 제작

HChaeEun 2023. 1. 9. 13:51

1️⃣prisma로 schema 설계하기

2️⃣댓글 삭제 API

3️⃣댓글 조회 API


📜prisma로 schema 설계하기

project ERD 중 comment 테이블을 create했다.

comment 테이블은 Users 테이블과 1:n관계이고,  Posts 테이블과도 1:n관계이다.

따라서 userId와 postId를 FK로 속성을 갖는다.

 

shema.prisma

model Users {
  userId           BigInt    @id @default(autoincrement())
  nickname         String?   @db.VarChar(10)
  name             String?   @db.VarChar(10)
  studentId        String?   @db.VarChar(10)
  department       String?   @db.VarChar(20)
  status           String    @db.VarChar(10)
  googleEmail      String?   @db.VarChar(50)
  googleNickname   String?   @db.VarChar(50)
  profileImagePath String?   @db.VarChar(200)
  comment          Comment[]
}

model Posts {
  postId      BigInt    @unique @default(autoincrement())
  userId      BigInt
  title       String?   @db.VarChar(200)
  content     String    @db.VarChar(500)
  imagePath   String?   @db.VarChar(200)
  publishDate DateTime  @default(now())
  place       String    @db.VarChar(100)
  status      String    @db.VarChar(20)
  comment     Comment[]
}

model Comment {
  commentId   BigInt   @id @default(autoincrement())
  user        Users?   @relation(fields: [userId], references: [userId])
  userId      BigInt?
  post        Posts?   @relation(fields: [postId], references: [postId])
  postId      BigInt?
  content     String?  @db.VarChar(500)
  commentDate DateTime @default(now())
}

?가 붙으면 null

?가 안 붙으면 not null (필수 값)

 

user과 post는 관계설정을 위한 일시적인 속성값으로

@relation(fields: [userId], references: [userId])는 필드의 userId는 Users 테이블의 userId 속성을 참조하는 관계임을 정의

참조: https://sdy-study.tistory.com/79

 

📜댓글 삭제 API

//댓글 삭제 API
app.delete('/post/:id/comment/:commentId', authenticateAccessToken, async (req, res) => {
    try {
        const postId = Number(req.params.id);
        const commentId = Number(req.params.commentId);
        const userId = req.user.userId;

        // commentId가 일치하는 댓글을 commentRes에 정보 저장
        const commentRes = await prisma.comment.findUnique({
            where: {
                commentId: commentId,
                postId: postId
            }
        })

        // commentRes에 저장된 userId와 현재 로그인 중인 user의 Id가 일치하는지 확인.
        if (commentRes.userId == userId) {
            await prisma.comment.delete({
                where: {
                    commentId: commentId,
                }
            });
            res.send({ message: 'Deleted Successfully.' });
        }
        else {
            res.status(403).send({ error: 'Authentication fail.' });
        }

    } catch (error) {
        console.error(error);
        res.status(500).send({ error: 'Server Error.' });
    }
});

(commentId:11)데이터 삭제 전

comment table에서 해당 데이터를 삭제하려고 한다. 테스트는 postman을 통해 진행

삭제 API 테스트
(commentId:11)데이터 삭제 후

파라미터로 받은 commentId와 postId에 일치하는 데이터를 찾아 userId가 일치하다는 것을 확인하고, 삭제되는 것을 확인

 

📜댓글 조회 API

//댓글 목록 조회 api (시간 순으로 오름차순 정렬하기)
app.get('/post/:id/comment', async (req, res) => {
    try {
        const postId = Number(req.params.id);
        
        const commentList = await prisma.comment.findMany({
            orderBy: [
                {
                    // commentDate 값이 일치하는 데이터들이 있을 수 있음. -> unique한 값을 갖고 생성순으로 ID값이 증가하는 PK로 정렬
                    commentId: 'asc',
                }
            ],
            where: {
                // postId가 일치하면 데이터 조회
                postId: postId
            },
            select: {
                userId: true,
                content: true,
                commentDate: true
            }
        });
        res.send(commentList);
    }
    catch (error) {
        console.error(error);
        res.status(500).send({ error: 'Server Error.' });
    }
});

(postId:2) 댓글 조회

prisma에 orderBy를 사용하여 정렬한다.

참조: https://www.prisma.io/docs/concepts/components/prisma-client/filtering-and-sorting

 

Filtering and sorting (Concepts)

Use the Prisma Client API to filter records by any combination of fields or related record fields, and sort the results.

www.prisma.io

정렬은 default가 오름차순 정렬이지만, 확실하게 정렬값을 설정하기 위해 코드를 작성했다.

'dev-log > web_study' 카테고리의 다른 글

[4주차]알림 시스템 API  (0) 2023.01.17
[2주차]Redis 구축 및 로그아웃 API 제작  (0) 2023.01.09