[2024.05.20 TIL] 내일배움캠프 24일차 (ORM, Prisma)

My_Code·2024년 5월 24일
0

TIL

목록 보기
32/113
post-thumbnail

본 내용은 내일배움캠프에서 활동한 내용을 기록한 글입니다.


💻 TIL(Today I Learned)

📌 Today I Done

✏️ ORM과 Prisma

  • ORM(Object Relational Mapping)은 말 그대로 JavaScript의 객체와 데이터베이스의 관계(Relation)를 연결해주는 도구들을 의미함

  • Prisma는 ORM의 한 종류로서, 관계형 데이터베이스를 사용할 수 있음

  • MySQL 뿐만 아니라 Oracle, MariaDB, PostgreSQL과 같은 다양한 데이터베이스를 사용할 수 있음


✏️ Prisma 시작하기

  • Prisma 라이브러리 설치하기
# yarn 프로젝트를 초기화합니다.
yarn init -y

# express, prisma, @prisma/client 라이브러리를 설치합니다.
yarn add express prisma @prisma/client

# nodemon 라이브러리를 DevDependency로 설치합니다.
yarn add -D nodemon

# 설치한 prisma를 초기화 하여, prisma를 사용할 수 있는 구조를 생성합니다.
npx prisma init
  • 디렉터리 구조: npx prisma init
내 프로젝트 폴더 이름
├── prisma
│   └── schema.prisma
├── .env
├── .gitignore
├── package.json
└── yarn.lock

✏️ Prisma model

  • Prisma의 model 구문은 특정 테이블과 컬럼의 속성값을 입력하여, 데이터베이스와 Express 프로젝트를 연결 시켜줌

  • schema.prisma : Posts 테이블 정의하기
// schema.prisma

model Posts {
  postId    Int      @id @default(autoincrement()) @map("postId")
  title     String   @map("title")
  content   String   @map("content") @db.Text
  password  String   @map("password")
  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  @@map("Posts")
}

✏️ Prisma DB와 Table 생성하기

  • prisma db pusb: DB, Table 생성하기
# schema.prisma 파일에 설정된 모델을 바탕으로 MySQL에 정보를 업로드합니다.
npx prisma db push

  • prisma_crud 데이터베이스 내부에 Posts 테이블이 생성됨

→ Prisma CLI 명령어에 대해 자세히 알고싶다면 여기를 클릭!


✏️ Prisma Method

  • Prisma 게시글 생성 API
// routes/posts.router.js

//게시글 생성 API
router.post('/posts', async (req, res, next) => {
    const { title, content, password } = req.body;

    const post = await prisma.posts.create({
        data: { title, content, password },
    });

    return res.status(201).json({ data: post });
});
  • Prisma 게시글 목록 조회 API
// routes/posts.router.js

// 게시글 목록 조회 API
router.get('/posts', async (req, res, next) => {
    // 게시글 내용 포함 X
    const posts = await prisma.posts.findMany({
        select: {
            postId: true,
            title: true,
            createdAt: true,
            updatedAt: true,
        },
    });

    return res.status(200).json({ data: posts });
});
  • Prisma 게시글 상세 조회 API
// routes/posts.router.js

// 게시글 목록 상세 조회 API
router.get('/posts/:postId', async (req, res, next) => {
    const { postId } = req.params;

    // 특정 게시글 하나만 찾을 때
    const post = await prisma.posts.findFirst({
        where: { postId: +postId },
        select: {
            postId: true,
            title: true,
            content: true,
            createdAt: true,
            updatedAt: true,
        },
    });

    return res.status(200).json({ data: post });
});
  • Prisma 게시글 수정 API
// routes/posts.router.js

// routes/posts.router.js

// 게시글 수정 API
router.put('/posts/:postId', async (req, res, next) => {
    const { postId } = req.params;
    const { title, content, password } = req.body;

    // 게시물이 있는지 확인
    const post = await prisma.posts.findUnique({
        where: { postId: +postId },
    });

    if (!post) {
        return res.status(404).json({ errorMessage: '게시글이 존재하지 않습니다.' });
    } else if (post.password !== password) {
        return res.status(401).json({ errorMessage: '비밀번호가 일치하지 않습니다.' });
    }

    // 게시글 수정
    await prisma.posts.update({
        data: { title, content },
        where: {
            postId: +postId,
            password: password,
        },
    });

    return res.status(200).json({ data: '게시글 수정이 완료되었습니다.' });
});
  • Prisma 게시글 삭제 API
// routes/posts.router.js

// 게시글 삭제 API
router.delete('/posts/:postId', async (req, res, next) => {
    const { postId } = req.params;
    const { password } = req.body;

    const post = await prisma.posts.findUnique({
        where: { postId: +postId },
    });

    if (!post) {
        return res.status(404).json({ errorMessage: '게시글이 존재하지 않습니다.' });
    } else if (post.password !== password) {
        return res.status(401).json({ errorMessage: '비밀번호가 일치하지 않습니다.' });
    }

    await prisma.posts.delete({
        where: { postId: +postId },
    });

    return res.status(200).json({ data: '게시글 삭제가 완료되었습니다.' });
});


📌 Tomorrow's Goal

✏️ 노드 숙련 강의 시청하기

  • 2주차 남은 강의를 시청

  • 최대한 시청 후 과제 문서를 작성할 수 있도록 노력할 것!!

  • 내일도 시간이 많지 않기 때문에 오전, 오후에 최대한 시청할 예정



📌 Today's Goal I Done

✔️ 노드 숙련 강의 시청하기

  • 예비군으로 밀린 강의를 시청함

  • 원래는 2주차를 오늘 안에 다 시청하려고 했으나, 생각보다 내용이 어려웠음

  • 완전히 막힌다기 보다는 내용이 어려워서 검색하면서 이해하느라 진행이 느렸음

  • 현재 2주차 1/3 정도 완료한 상태

  • 주말을 이용해서 최대한 강의를 들을 예정


profile
조금씩 정리하자!!!

0개의 댓글