Search code examples
typescriptexpressnestjstypeorm

TypeORM default/force values on table


I'm working in a project with TypeORM (MariaDB) in NestJS, I have a "groups" tables, it has a 'name' and 'permissions' columns, I want to set values for this table with ADMIN and DEFAULT roles. These roles shouldn't be able to be removed (They also have a column 'deleteable' as boolean).

I'm new using TypeORM and SQL databases and I don't know what I have to do to solve this.


Solution

  • I found the answer, "onModuleInit" (from Lifecycle events) method inside a module, this method will be called every time module is loaded (also after database connection):

    @Module({...})
    export class RolesModule {
      constructor(
        @InjectRepository(RoleEntity)
        private readonly repository: Repository<RoleEntity>,
      ) {}
    
      async onModuleInit() {
        // Use "repository" to interact with table and create default values in case roles not exists.
      }
    }