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

package.json view raw
"seed:config": "ts-node ./node_modules/typeorm-seeding/dist/cli.js config",
"seed:run": "ts-node ./node_modules/typeorm-seeding/dist/cli.js seed"

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)

src/database/seeds/create-products.seed.ts view raw
import { Product } from '../../modules/products/entities/product.entity';
import { Connection } from 'typeorm';
import { Factory, Seeder } from 'typeorm-seeding';

export default class CreateProducts implements Seeder {
  public async run(factory: Factory, connection: Connection): Promise<any> {
    await connection
      .createQueryBuilder()
      .insert()
      .into(Product)
      .values([
        {
          name: 'Berries',
          unitPrice: 23.54,
          description:
            'The bestest fruit known to man. Sweet yet sour but beautiful',
          image: '/assets/images/berries.jpeg',
        },
        {
          name: 'Orange',
          unitPrice: 10.33,
          description: `Succulent and watery, you'll never run out of water`,
          image: '/assets/images/oranges.jpeg',
        },
        {
          name: 'Lemons',
          unitPrice: 12.13,
          description: 'Sour but important for revitalization',
          image: '/assets/images/lemons.jpeg',
        },
        {
          name: 'Bananas',
          unitPrice: 10.33,
          description: 'An every day fruit, can be served with every dish',
          image: '/assets/images/banana.jpeg',
        },
        {
          name: 'Apples',
          unitPrice: 10.33,
          description:
            'Sliced and served with your salad. Served as snacks midway through the day',
          image: '/assets/images/apple-item.png',
        },
        {
          name: 'Sharifa',
          unitPrice: 10.33,
          description: 'A great fruit, also known as custard apple',
          image: '/assets/images/unknown.jpeg',
        },
      ])
      .execute();
  }
}

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:

Products Table