[TIL]Prisma_Seeding

Sohee Yeo·2024년 1월 3일
0
post-thumbnail

Prisma Seeding

Database Seeding은 초기 데이터 셋으로 데이터베이스를 채우는 것을 의미한다. Prisma에서 Database Seed하는 방법을 알아보려 한다.

seed.js 파일 생성

/prisma 폴더 안에 seed.js 파일을 생성한다.

seed.js 파일 작성

prisma.schema에서 User, Post 모델을 정의했다고 가정해보자. User에 새로운 Post를 추가하는 스크립트를 작성해보자.

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

const prisma = new PrismaClient();

// name이 Kim인 데이터가 없다면 생성
async function main() {
  const data = await prisma.user.upsert({
    where: { name: 'Kim' },
    update: {},
    create: {
      name: 'Kim',
      posts: {
        create: {
          title: 'new title',
          content: 'new content',
        },
      },
    },
  })
  console.log({ data });
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })

배열 형식의 데이터로 seed를 진행할 수도 있다.

// /util/data.js

const users = [
  { name: 'User1' }, 
  { name: 'User2' }, 
  { name: 'User3' },
  { name: 'User4' }
  { name: 'User5' }
  { name: 'User6' }
  { name: 'User7' }
  { name: 'User8' }
...
]

export default users;
// /prisma/seed.js
import { PrismaClient } from "@prisma/client";
import users from "../util/data.js"

const prisma = new PrismaClient();

async function main() {
  for(let user of users) {
    const userData = await prisma.user.create({
      data: user,
  });
  console.log({ data });
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })

package.json 파일 수정

package.json 파일의 "prisma" 키에 "seed" 키를 추가한다.

// package.json
...
"prisma": {
  "seed": "node prisma/seed.js"
},

Seeding

터미널에 아래 명령어를 입력하여 seed를 진행한다.

npx prisma db seed

💥참고) Next.js_import 오류

seed를 진행하는 명령어를 입력했지만, 아래와 같은 에러가 발생했다.
SyntaxError: Cannot use import statement outside a module

에러를 해결하기 전에 CommnJSES modules에 대해 간단히 짚어보자.

CommonJS : require(), module.exports 키워드를 사용하여 모듈에 접근
ES modules : import, export 키워드를 사용하여 모듈에 접근

발생 원인

Node.js에서는 기본적으로 CommonJS를 제공해왔다. package.json 파일에 "type" 필드가 없거나 "type": "commonjs" 가 포함되었다면, JS 파일은 CommonJS로 처리된다. import 키워드를 사용하기 위해서는 ES modules로 처리한다는 것을 명시해야 하는데, 명시하지 않았기 때문에 에러가 발생한 것이다.

📍 하지만 Next.js 12부터 ES modules를 지원한다는데 왜 문제가 발생한 것일까..?
next.config.js 파일은 ES modules를 지원하지 않는다고 한다. 또한 node를 사용하여 npm 스크립트를 실행하면 이와 같은 문제가 발생할 수 있다고 한다.

해결 방법

package.json 파일에 "type": "commonjs"를 추가해준다.

{
    "name": "next_prisma",
    "version": "0.1.0",
    "type": "module",
  ...
}

next.config.jsnext.config.mjs로 확장자를 변경한 후 파일 안의 module.exportsexport default로 바꿔준다.

// next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;



참고

https://www.prisma.io/docs/orm/prisma-migrate/workflows/seeding

https://www.codeconcisely.com/posts/nextjs-esm/

https://nodejs.org/api/packages.html#type

profile
실패에 무딘 사람. 프론트엔드 개발자를 꿈꿉니다

0개의 댓글