First of all, data seeding is the mechanism of populating a database with dummy data. It is very useful in development of any system. It helps in automated testing and also increases the efficiency of database management.
Data seeding can be done in several ways, but in this blog we are going to use faker npm package so seed data into existing database.
Pre-requisites
You will need an existing NestJs project with Prisma as the default ORM to handle database.
Get started
Assuming that you have a NestJs project with Prisma as ORM, firstly, you have to install a package named faker in the project. You can do it by running the following command in the terminal:
npm install @faker-js/faker --save-dev
After that, you can create your data model in prisma.schema file. Let’s take an example of a User model and create it inside schema as follow:
//prisma.schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Now that you have created your model, you have to migrate it to your database to be in sync. Run the following commands in the terminal :
npx prisma generate
npx prisma migrate dev --name init
Now, the next step is to create a seed.ts file inside prisma folder where we are going to write the logic behind data seeding. The seed.ts file should look like following:
//seed.ts
import { PrismaClient } from '@prisma/client';
import {faker} from '@faker-js/faker';
const prisma = new PrismaClient();
const generateUsers = (count) => {
const users = [];
for (let i = 0; i < count; i++) {
users.push({
name: faker.internet.userName(),
email: faker.internet.email(),
password: faker.internet.password(),
createdAt: new Date(),
updatedAt: new Date(),
});
}
return users;
};
const seed = async () => {
const users = generateUsers(10);
for (let user of users) {
await prisma.user.create({ data: user });
}
console.log('Seed data completed!');
};
seed()
.catch((error) => console.error(error))
.finally(async () => {
await prisma.$disconnect();
});
Since, all the coding part is completed, you have to add the following script in your package.json file:
{
...
"scripts":{
...
"seed": "ts-node prisma/seed.ts"
}
...
}
Now you can run it by following command in terminal:
npm run seed
To check if your database is seeded or not, you can open prisma studio and check it.
npx prisma studio
So, this is how you seed a database using faker package. To learn more about data seeding, you can always visit the official docs by clicking here.