Lewis Tyler

Prisma seed data example using Faker

Meaningful test data makes local development a lot more enjoyable, in my opinion. That’s because the process of creating test data, if not automated, can be a huge bore.

If you are using the ORM Prisma, here’s a little seed script to get your local dev going.

// app/prisma/seed.ts
import { PrismaClient, User } from "@prisma/client";
import { faker } from "@faker-js/faker";

const prisma = new PrismaClient();

async function main() {
  await prisma.user.deleteMany({}); // use with caution.

  const amountOfUsers = 50;

  const users: User[] = [];

  for (let i = 0; i < amountOfUsers; i++) {
    const firstName = faker.name.firstName()
    const lastName = faker.name.lastName()

    const user: User = {
      id: i,
      sub: faker.datatype.uuid(),
      email: faker.internet.email(firstName, lastName),
      firstName,
      lastName,
      phone: faker.phone.phoneNumber(),
      emailVerified: !(i % 7 === 0),
      timezone: "America/New_York",
      createdAt: faker.date.past(),
      updatedAt: faker.date.recent(),
    };

    users.push(user);
  }

  const addUsers = async () => await prisma.user.createMany({ data: users });

  addUsers();
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
// app/prisma/schema.prisma
model User {
  id            Int      @id @default(autoincrement())
  sub           String   @unique
  email         String   @unique
  phone         String   @unique
  firstName     String   @db.VarChar(200)
  lastName      String   @db.VarChar(200)
  timezone      String?
  emailVerified Boolean  @default(false)
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
}
// package.json
{
  "prisma": {
    "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
  },
}

To use:

npx prisma db seed