[Prisma, PlanetScale] 맛보기 2탄

nyongho·2023년 10월 6일
0

NextJS

목록 보기
6/6

PlanetScale, Prisma를 이용해 회원가입 로직을 만들어보자!

다시 한 번 상기하자면 Prisma는 Node.js와 Typescript를 이용한 Database ORM (Object Relational Mapping, 객체와 데이터베이스 관계를 매핑)이다.

먼저 Prisma Client를 초기화 하고 내보내준다.

// libs/server/client.ts

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

export default new PrismaClient();

그리고 Prisma를 통해 DB를 선택하고 DB 모델을 생성할 Provider를 선택, 마지막으로 데이터 모델을 정의하고 관계를 정립한다.

// 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     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

model User {
  id        Int      @id @default(autoincrement())
  phone     Int?     @unique
  email     String?  @unique
  name      String
  avatar    String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  Token     Token[]
}

이렇게 데이터 모델을 정의했으면 이를 바탕으로 API를 만들어보자. 회원가입 혹은 로그인 때 휴대폰 번호 or 이메일을 입력 받을 것이다.

이를 위한 로직은 다음과 같다.

Phone or Email 입력 => User 모델에서 찾기 => User 모델에 이미 존재 ? 토큰 발급 : 신규 생성

// pages/api/users/enter.tsx
async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { email, phone } = req.body;

  const payload = phone ? { phone: +phone } : { email }

  const user = await client.user.upsert({
    // 휴대폰 번호로 찾기
    where: {
      ...payload,
    },
    // 없으면 신규 생성
    create: {
      name: 'Anonymous',
      ...payload,
    },
    update: {}
  })
  const token = await client.token.
  console.log(user);
  res.status(200).end();
}

profile
두 줄 소개

0개의 댓글