Create Nest.js Seeders
This article is Part 4 in a 10 Part Series.
- Part 1 - Bootstrapping a Nest.js Project on Ubuntu
- Part 2 - Create Nest.js Migrations
- Part 3 - Create Nest.js CRUD Resources
- Part 4 - This Article
- Part 5 - Create a Customer Module in Nest.js
- Part 6 - Nest.js Authentication
- Part 7 - Create a Products Module in Nest.js
- Part 8 - Create a Stripe Module in Nest.js
- Part 9 - Create an Orders Module in Nest.js
- Part 10 - End to End Tests for our Storefront Backend
In the previous tutorial, we created the CRUD resources as well as the entities that our storefront backend would require. Today, we shall be creating a special class called a database seeder, which is used for populating a database with some initial data, usually for testing or development purposes, without having to manually key in data (which is quite tedious).
For our project, we shall be using the typeorm-seeding library, which I have found out to be the most straightforward.
In case of any issues, you can refer to my Github repository here.
Add the typeorm seeder package (but let it only work in the development environment)
npm i typeorm-seeding --save-dev
Create a package.json entry for the seeder tasks
Check the seeder configuration
npm run seed:config
Output:
🌱 TypeORM Seeding v1.6.1
{
type: 'postgres',
logging: 'true',
host: 'localhost',
port: 5432,
username: 'storefront_username',
password: 'storefront_password',
database: 'storefront_database',
autoLoadEntities: true,
ssl: { rejectUnauthorized: false },
entities: [
'/home/my_profile/Projects/nest_projects/storefront-backend/src/modules/**/*.entity{.ts,.js}',
'/home/my_profile/Projects/nest_projects/storefront-backend/src/modules/**/*.view{.ts,.js}'
],
migrations: [
'/home/my_profile/Projects/nest_projects/storefront-backend/src/migrations/**/*{.ts,.js}'
],
cli: {
migrationsDir: '/home/my_profile/Projects/nest_projects/storefront-backend/src//migrations'
},
baseDirectory: '/home/my_profile/Projects/nest_projects/storefront-backend',
factories: [ 'src/database/factories/**/*{.ts,.js}' ],
seeds: [ 'src/database/seeds/**/*{.ts,.js}' ]
}
Create the seeder (I’ve called mine create-products.seed)
Run the seeder
npm run seed:run
Output:
🌱 TypeORM Seeding v1.6.1
✔ ORM Config loaded
✔ Factories are imported
✔ Seeders are imported
✔ Database connected
✔ Seeder CreateProducts executed
👍 Finished Seeding
Now, when you run a SELECT query on the products table, you’ll notice that the table now has some initial data: