Search code examples
nestjsseeding

How to create Seed in Nestjs?


I have my application with this directory structure.

App
|-- src
    |-- modules
        |-- user
        |-- role
        |-- company
        |-- ...
        |-- app.module.ts
        |-- main.js (Application Bootstrap)
        |-- seed.js
    |-- ...other files

I created a file with the following content:

seed.ts

enter image description here

I want to insert data at the beginning of the application to complete with data some tables of my databases that are needed for the application to work.

Thanks for the help!


Solution

  • Well, let's make it easier, You have two options for seeding, use queryRunner.manager.insert() in your migration files, and make application to run migrations every time you run it!

    In AppService implement OnApplicationBootstrap and then invoke its function, whatever you write in that function will be called each time you run the application, here's a sample:

    
    @Injectable()
    export class AppService implements OnApplicationBootstrap{
      onApplicationBootstrap(): any {
      // add a functionality to check if the data already exists, if not add it manually
      }
    }