Next.js에서 Prisma사용해 간단하게 API 구현하기 [Nextjs]

김대운·2023년 4월 19일
0

Nextjs

목록 보기
1/4
post-thumbnail

Prisma란?

Prisma는 데이터베이스를 다루는 데 사용되는 오픈 소스 ORM(Object-Relational Mapping) 라이브러리입니다. Prisma를 사용하면, SQL 쿼리를 직접 작성하지 않고도 안전한 API를 사용하여 데이터베이스에 액세스 할 수 있습니다.

ORM(Object-Relational Mapping) 이란?

  • ORM은 객체와 데이터베이스 간의 매핑을 자동으로 처리하여, 개발자가 SQL 쿼리를 작성하지 않아도 객체를 데이터베이스에 저장하거나 검색할 수 있게 합니다. 즉, 객체 지향 코드를 작성하면, ORM은 해당 객체를 데이터베이스 테이블과 매핑하여 자동으로 적절한 SQL 쿼리를 생성하고 실행합니다.

  • ORM을 사용하면, 개발자는 데이터베이스와의 상호작용을 추상화하여 비즈니스 로직에 집중할 수 있습니다. 또한 ORM은 데이터베이스와의 의존성을 낮추어, 데이터베이스 변경에 유연하게 대처할 수 있게 합니다.

Prisma의 장점은 ??

  1. 타입 안전성: Prisma는 데이터 모델을 정의할 때 타입 체크를 수행합니다. 이를 통해 개발자는 컴파일 시점에서 타입 불일치 오류를 방지할 수 있습니다. 따라서 코드의 안정성과 유지 보수성을 높일 수 있습니다.

  2. 타이트한 통합: Prisma는 다양한 데이터베이스 시스템과 타이트하게 통합됩니다. 데이터베이스 스키마를 정의하는 GraphQL SDL을 사용하여 Prisma가 자동으로 데이터베이스와 타입 매핑 및 SQL 쿼리를 생성합니다. 이를 통해 개발자는 데이터베이스 작업을 보다 쉽게 처리할 수 있습니다.

  3. 성능: Prisma는 높은 성능을 제공합니다. Prisma는 일관된 캐싱 및 쿼리 최적화를 사용하여 데이터베이스 작업을 최적화합니다.

  1. 오픈 소스: Prisma는 오픈 소스 라이브러리로 제공되며, 커뮤니티에서 활발하게 개발되고 있습니다. 따라서 개발자들은 Prisma를 사용하여 데이터베이스 작업을 보다 쉽게 처리할 수 있습니다.

Next.js13에서 prisma 사용 하기

  1. Prisma 설치: 우선, Prisma를 설치해야 합니다. npm을 사용하여 다음 명령어를 실행합니다.
npm install prisma
  1. Prisma 데이터 모델 정의: 다음으로, Prisma 데이터 모델을 정의해야 합니다.

이를 위해 prisma/schema.prisma 파일을 생성하고, 필요한 모델과 필드를 정의합니다. 예를 들어, User 모델을 정의하고 필요한 필드를 추가할 수 있습니다.

/prisma/schema.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 = "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


}


  • 위의 코드는 MongoDB 데이터베이스를 사용하는 애플리케이션의 데이터 모델을 정의하는데, generator, datasource, model 등의 Prisma 스키마 요소를 포함합니다.

  • generator 요소는 추후에 생성하는 Prisma client 사용하는데 필요합니다.
    provider에 prisma-client-js를 추가해주시면 됩니다.

  • datasource 요소는 데이터베이스 연결 정보를 정의하는 데 사용됩니다. 위의 코드에서는 mongodb 데이터 소스를 사용하며, url에 데이터베이스 연결 url을 작성하면 됩니다.

  • model 요소는 데이터 모델을 정의합니다.
    위의 코드에서는 User, Account, Listing 모델을 정의하며, 각 모델은 필드와 관계를 정의합니다.
    예를 들어, User 모델은 id, name, email 등의 필드 accounts, listings 같은 관계를 정의합니다.

  1. 스키마를 작성 또는 수정 후에 해당 변경 사항을 데이터 베이스에 저장해줘야합니다.
npx prisma db push 

이 명령어를 실행하면 Prisma는 데이터베이스와 Prisma 스키마 간의 차이를 검사하고, 변경 사항을 데이터베이스에 적용합니다.

  1. 데이터베이스와 상호작용하기 위해 prisma/client 설치하고 설정해주기
npm install @prisma/client

위 명령어를 통해 설치 후

/libs/prismadb.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

위와 같은 코드를 작성했다면 client변수를 통해 데이터 베이스와 상호작용하는 api를 생성할 수 있습니다.

  1. nextjs13 api route기능을 사용하여 api 생성하기

api route 기능이란 ?
위 링크를 방문하시면 api route기능이 무엇인지 설명되어있습니다 !

/app/api/register/rote.ts 
import { NextResponse } from 'next/server'
import bcrypt from 'bcrypt'

import prisma from '@/app/libs/prismadb'

export async function POST(request: Request) {
  const body = await request.json()
  const { email, name, password } = body

  const hashedPassword = await bcrypt.hash(password, 12)

  const user = await prisma.user.create({
    data: {
      email,
      name,
      hashedPassword,
    },
  })

  return NextResponse.json(user)
}
/app/actions/getCurrentUser.ts
import { getServerSession } from 'next-auth/next'

import { authOptions } from '@/pages/api/auth/[...nextauth]'
import prisma from '@/app/libs/prismadb'

export async function getSession() {
  return await getServerSession(authOptions)
}

export default async function getCurrentUser() {
  try {
    const session = await getSession()

    if (!session?.user?.email) {
      return null
    }

    const currentUser = await prisma.user.findUnique({
      where: {
        email: session.user.email as string,
      },
    })

    if (!currentUser) {
      return null
    }

    return {
      ...currentUser,
      createdAt: currentUser.createdAt.toISOString(),
      updatedAt: currentUser.updatedAt.toISOString(),
      emailVerified: currentUser.emailVerified?.toISOString() || null,
    }
  } catch (error: any) {
    return null
  }
}

위 두 코드 처럼 회원가입 기능을 하는 POST API와
user 정보를 받아오는 API를 간단하게 구현하여 컴포넌트에서 바로 사용할 수 있습니다.

0개의 댓글