[Prisma] Database Seeding

aqualung·2024년 7월 22일

처음 앱을 시작할 때 관리자계정 같은 초기 데이터를 넣어주고 싶었다.

Seeding, 말 그대로 씨앗을 처음 심어주는거다.

노드 환경에서 Prisma를 이용하여 진행하였다.


Prisma Seeding

공식문서에 친절하게 잘 나와있다.

  1. package.json에 다음의 데이터를 추가한다.
"prisma": {
  "seed": "ts-node prisma/seed.ts"
},

seed.ts의 경로를 올바르게 작성해주어야 한다.

  1. seed.ts를 작성해준다. seed.ts는 데이터를 생성하는 스크립트다.
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
/*
To resolve json file
-> tsconfig.json
"esModuleInterop": true,
"resolveJsonModule": true
*/
import categoryData from '../data/category.json';

const prisma = new PrismaClient();

async function hash(text: string) {
  const saltOrRounds = 10;
  const hashedToken = await bcrypt.hash(text, saltOrRounds);
  return hashedToken;
}

async function main() {
  return prisma.$transaction(async (tx) => {
    // seed admin user
    const hashedPassword = await hash(process.env.ADMIN_PASSWORD);
    await tx.user.upsert({
      where: {
        id: 1,
      },
      update: {},
      create: {
        id: 1,
        email: 'admin',
        nickname: 'admin',
        password: hashedPassword,
      },
    });

    // seed categories
    const categories = Object.values(categoryData);
    for (const category of categories) {
      await tx.category.upsert({
        where: {
          id: category.id,
        },
        update: {},
        create: {
          id: category.id,
          title: category.label,
        },
      });
    }
  });
}

main()
  .catch((e) => console.error(e))
  .finally(() => prisma.$disconnect());
  • 어떤 메소드를 사용할지 생각해봐야 했다. 나는 upsert를 사용했는데 앱을 실행할 때마다 Seed를 하도록 설정해 놨기 때문이다.
  • 초기값으로 JSON 파일 가져다 쓰기 위해 tsconfig를 주석처럼 설정해줬다. (혹은 fsreadFile등을 이용할 수도 있다.)
  1. npx prisma db seed 명령어를 실행한다.
    해당 명령어로 1번에서 설정한 ts-node prisma/seed.ts가 실행된다.

0개의 댓글