LoginSignup
6
1

More than 1 year has passed since last update.

Prisma+fakerでサクッとデモデータを作る

Last updated at Posted at 2022-12-13

Prisma+fakerでサクッとデモデータを作る

MYJLab Advent Calendar 2022、14日目の記事、担当は3年の@takumiakasaka1231です!

昨日の記事は、@mahirooooonWord2Vecについてでした。

言葉の足し算引き算が楽しいらしく、授業後に目をキラキラさせながらお話していたのを思い出しました。(笑)

さて、本日は、モダンなORMであるprismaとfakerを使って、サクッとデモデータをDB内に入れていってみようと思います!

では、僕の初qiita記事、スタートです!

公式ducument

背景

backend開発の時、DBにデモデータをいれるのが面倒くさいときってありますよね?

そんなときに劇的に開発効率を上げてくれる方法があります。

(seedで、チーム全員でデモデータをそろえたいときは、この手法は向いていません)

環境構築(prisma,faker,mysql)

prismaのinstall(node 14.17.0以上が必要らしいです)(そこでめっちゃ怒られた)

npm init -y 
npm install typescript ts-node @types/node --save-dev
npx tsc --init
npm install prisma --save-dev
npx prisma init --datasource-provider sqlite

fakerのinstall

npm install @faker-js/faker --save-dev

localでmysqlを立ち上げてください

docker pull mysql
docker run --name your-container-name -e MYSQL_ROOT_PASSWORD=your-password -d -p 3306:3306 mysql:tag

これで環境が整いました。

ファイルの中身

これらのコマンドを実行した後、ファイルがいろいろできたと思います。
今回は、関連する部分だけ

  • prisma/schema.prisma

DBの中身を実際に書いていく部分になります。

早速、中身を変更していきましょう。

schemaの変更

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")
}

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

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

.envにDATABASE_URLの追加をお忘れなく

そしたら、migrateをしていきます

npx prisma migrate dev --name init

次は、実際にデータを入れるseed.tsを用意していきましょう!

seed.ts

まずは、package.jsonに以下を追加します。

"prisma": {
    "seed": "ts-node prisma/seed.ts"
  }

これで、seed.tsを実行する準備が完了しました。
次に、実際のファイルを作成、編集していきましょう。

image.png

prismaフォルダー下にseed.tsを作成します

seed.tsを以下のように記述します。

import { PrismaClient } from "@prisma/client";
import { faker } from "@faker-js/faker";

const prisma = new PrismaClient();
async function main() {
  for (let index = 0; index < 100; index++) {
    await prisma.user.create({
      data: {
        name: faker.name.fullName(),
        email: faker.internet.email(),
        posts: {
          createMany: {
            data: [
              {
                title: faker.name.jobTitle(),
              },
              {
                title: faker.name.jobTitle(),
              },
              {
                title: faker.name.jobTitle(),
              },
              {
                title: faker.name.jobTitle(),
              },
              {
                title: faker.name.jobTitle(),
              },
            ],
          },
        },
      },
    });
  }
}
main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });

その後、seed.tsを動かしていきます

npx prisma migrate reset
🌱  The seed command has been executed.

と表示されれば成功です!!

prisma studioを覗きに行きましょう

npx prisma studio

image.png

完璧です。

100人と、1人につき5つ投稿が紐づいたデモデータを作成することができました!!!

終わりに

どうでしたか?

初投稿の記事となりますが、皆さまの知識になったり、参考になれば幸いです。

これを機に、たくさん投稿したいです!

ではまたっ!!!

参考文献

prisma 公式ドキュメント

faker.js 公式ドキュメント

Seeding Database with Prisma & Faker -by Leigh Halliday

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1