본문 바로가기
Node js/Nest js 강의 내용

5-1. prisma 기본

by Bill Lab 2024. 12. 6.
728x90

1. 왜 Prisma 인가?

    : https://www.prisma.io/docs/orm/more/comparisons/prisma-and-typeorm

 

Prisma ORM vs TypeORM | Prisma Documentation

Learn how Prisma compares to TypeORM.

www.prisma.io

 

  TypeORM Prisma
종합 기존의 ORM으로, 데이터베이스 테이블을
클래스 모델로 매핑
최신화된 ORM으로, 기존 ORM에서 발생하는 문제
(복잡한 모델 인스턴스, 비즈니스 로직과 저장 로직의 혼합, 타입 안정성 부족 등)를 해결
객체관리 entity 객체의 관리를 통해 DB 와 mapping Prisma 스키마로 데이터 모델 관리
프로그램밍 측면 객체 지향 프로그래밍(OOP) 기반 더 간결하고 명시적이며, SQL에 가까운
추상화 레벨을 제공
query  Repository 또는 QueryBuilder를 사용 함수형 쿼리를 실행
type safe 기본적으로 타입스크립트를 지원하지만,
런타임 시 타입 오류가 발생
강력한 타입 안전성을 제공

 

 

2. 작업 순서 및 세팅 방법

https://www.prisma.io/docs/getting-started/quickstart-sqlite

 

Quickstart with TypeScript & SQLite | Prisma Documentation

Get started with Prisma ORM in 5 minutes. You will learn how to send queries to a SQLite database in a plain TypeScript script using Prisma Client.

www.prisma.io

https://docs.nestjs.com/recipes/prisma

 

     1) DB 생성

        : 앞에 생성한 script 로 db table 생성하여 show tables로 table 확인!

     2) npm 설치

pnpm install prisma --save-dev

     2) config 세팅(접속 url 포함)

npx prisma init

prisma 폴더 내 schema.prisma

     3) 스키마 생성(자동)

 npx prisma db pull

 

     4) client 생성

         : 이후 필요한 entity model 이 자동 생성 되었을 때 참조하기 위해 사용

npm install @prisma/client
yarn build or pnpm build

 

   

      5-1) prisma generate 

            : Prisma Client를 자동 생성한다.

             (entity 의 역할을 자동으로 수행)

npx prisma generate

 

출처: nest 공식 사이트

 

     5-2) prisma migrate 이용

       : 물론 일반적인 ORM 순서처럼 진행해도 된다.(schema 파일 생성 후 migrate을 통해 DB 반영

        (하지만, schema 파일의 가독성과 작업이 사용자 친화적이지 않으므로 migrate방식은 추천하지 않는다.)

 

     6) 각 module 내 PrismaModule import

     

     7) repository 개발

     8) 서비스 layer 에 적용

         

 

3. 스키마 구조

model cart {
  id         Int       @id
  product_id Int?
  unit_price Int?
  qty        Int?
  created_at DateTime? @db.Timestamp(0)
  updated_at DateTime? @db.Timestamp(0)
}

model order {
  id          Int           @id
  customer_id Int?
  order_no    String?       @db.VarChar(255)
  total_price Int?
  status      String?
  created_at  DateTime?     @db.Timestamp(0)
  updated_at  DateTime?     @db.Timestamp(0)
}

model ordersdetail {
  id         Int       @id
  order_no   String?   @db.VarChar(255)
  product_id Int?
  unit_price Int?
  qty        Int?
  created_at DateTime? @db.Timestamp(0)
  updated_at DateTime? @db.Timestamp(0)
}

model product {
  id          Int     @id
  productname String? @db.VarChar(255)
  price       Int?
  qty         Int?
}

 

   

 

 

4. DB Data 생성 기본 예시

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  const user = await prisma.user.create({
    data: {
      name: 'Alice',
      email: 'alice@prisma.io',
    },
  })
  console.log(user)
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })

 

 

5. DB Data 조회 기본 예시

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  const users = await prisma.user.findMany()
  console.log(users)
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })

 

 

728x90