Javascript/Nest JS

[Chat App] prisma

  • -
728x90

Prisma는 Django ORM, Sequelize 등과 같은 자바스크립트와 타입스크립트 커뮤니티에서 주목받고 있는 차세대 ORM(Object Relational Mapping) 프레임워크이다.

 

Prisma는 어떤 데이터베이스를 사용하든 동일한 방식으로 데이터 모델링을 할 수 있도록 자체적인 스키마 문법을 제공하고 있다.

설치

우선 라이브러리를 설치 해주고, prisma cli를 사용하여 간단한 db작업을 위한 sqlite를 사용해보자.

 

yarn add -D prisma

npx prisma init --datasource-provider sqlite

 

 

설치를 완료하고나면 .env파일과 prisma폴더가 생성된다. database 경로를 위한 환경변수인데 나는 .env파일을 삭제하고 기존에 있던 .env.local로 옮겨주었다.

 

설정

prisma 폴더에 shcema.prisma에서 내가 사용할 데이터베이스의 데이터 모델링을 할 수 있다.

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

기본적으로 위와 같은 코드를 제공하고, prisma 공식문서를 보면서 필요한 모델을 모델링해보자.

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

 

Quickstart with TypeScript & SQLite

Get started with Prisma 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

User 모델만 간단하게 생성해보자.

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}

 

그 다음 스키마로 만든 모델을 마이그레이션 하여 데이터베이스 테이블을 생성해주자.

 

npx prisma migrate dev --name init

 

마이그레이션 하자마자 에러 .... db url을 찾을수 없다는 에러가 ... 아마도 .env.local로 옮겨서 그런듯한데...

https://www.prisma.io/docs/guides/development-environment/environment-variables/using-multiple-env-files

 

Using multiple .env files.

Learn how to set up a dedicated testing environment using multiple .env files.

www.prisma.io

해결 방법은 공식문서에서 확인할 수 있는데, dotenv-cli를 설치하여 강제로 특정 환경파일을 마이그레이션 전에 가져오는 방식이라고 한다.

음 .. 우선은 그냥 .env파일을 만들고 .gitignore에 넣어야겠다.

마이그레이션에 성공하면 위와같이 파일들이 생성된다.

 

npx prisma studio

 

위 명령어를 터미널에 입력하면 아래와 같이 gui형태로 db를 관리 할 수 있다.

 

 

 

src/lib/prisma.ts

import { PrismaClient } from "@prisma/client";

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma = globalForPrisma.prisma || new PrismaClient();

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

export default prisma;

프로젝트에서 prisma client를 사용할 때마다 인스턴스를 생성해야하는데, 위 코드는 매번 새 인스턴스를 인스턴스화 하지 않아도 되게 해주는 코드이다.

 

 

기본적인 Prisma 설정은 여기까지 하고, 유저 회원가입, 로그인 처리 등을 다뤄봐야겠다.

728x90
300x250
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.