Prisma

peace kim·2023년 12월 25일

Next-Airbnb

목록 보기
2/6
post-thumbnail

Prisma

Prisma는 ORM(Object-Relational Mapping, 객체 관계 연결)이다. Prisma는 어플리케이션에서 요청하는 모델을 mongodb로 정의할 수 있다는 장점을 가지고 있다. Prisma는 전통적인 ORM들을 대체하고 데이터 베이스들의 workflow를 간단하게 만들어준다. workflow는 총 3가지 측면에서 장점을 가진다.

Access: Type-safe database access with the auto-generated Prisma client (in JavaScript, TypeScript, Go)
Migrate: Declarative data modelling and migrations (optional)
Manage: Visual data management with Prisma Admin
Prisma는 GraphQL, REST, gRPC 같은 API를 만드는데 많이 활용되며 MySQL, PostgreSQL, MongoDB등을 지원한다.

Prisma 작동방식

Prisma Schema
Prisma 를 사용하기 전에 schema.prisma 파일을 통해 데이터베이스가 어떻게 생겼는지 알려줘야 한다.
schema.prisma 는 데이터베이스에 대한 모든 설명을 담은 파일.

모든 프로젝트는 Prisma schema file 과 Prisma toolkit 으로 시작한다.
Prisma Schema 는 개발자에게 직관적인 데이터 모델링 언어로 application models 를 정의할 수 있게 해준다.
이는 또한 db 와 generator 의 정의를 연결해준다.

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

model User {
  id              String @id @default(auto()) @map("_id") @db.ObjectId
  name            String?
  email           String?   @unique
  emailVerified   DateTime?
  image           String?
  hashedPassword  String?
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
  favoriteIds     String[] @db.ObjectId

  accounts Account[]
  listings Listing[]
  reservations Reservation[]
}
Prisma schema 는 강력한 데이터 모델링 기능을 가지고 있습니다.
예를들어, "Prisma-level" relation fields 를 정의할 수 있게 해줍니다.

Data source: 데이터베이스 연결을 명시함 (환경변수를 통해)
Generator: 생성하길 원하는 Prisma Client를 지시함
Data model: 어플리케이션의 모델을 정의함

Prisma data model

데이터 모델은 model의 집합을 의미함
각각의 모델은 RDB의 테이블 또는 몽고DB의 컬렉션을 의미하며, Prisma 클라이언트 API에서 쿼리의 대상이 됨
데이터 모델은 Prisma에서 스키마를 작성해 DB에 푸시할수도 있고, 반대로 DB에 이미 있는 테이블을 조회해 prisma에 가져올수도 있음
Install
다음의 커맨드 입력

npm install @prisma/client 

설치이후 해당 폴더에서 prisma generate 실행
설정 완료후 클라이언트에서 PrismaClient를 가져와 사용

lib 폴더를 만들고 그 안에 prisma.ts 를 만들어주는 명령어다

import { PrismaClient } from "@prisma/client"

declare global {
  var prisma: PrismaClient | undefined
}

const client = globalThis.prisma || new PrismaClient()
if (process.env.NODE_ENV !== "production") globalThis.prisma = client

export default client

Next.js에는 Prisma를 많이 사용하길래 Prisma를 사용하기로 하였다.

Prisma를 연결했으니 구글로 소셜 로그인을 만들어볼것이다

profile
개발자

0개의 댓글