Reducing boilerplate

There's an interesting alternative to the injection of the configuration namespace in the dynamic module.

Here, I'll just show another approach to injecting the configuration namespace in TypeORM's dynamic module configuration, but feel free to choose either one according to your preference.

If you notice, three options are being used to configure the TypeOrmModule, which are type, url and autoLoadEntities. What we can do is to already have all these options set in the configuration namespace, and with that, inject it in a much less verbose way.

We can return to the database.config file and have all those options configured here, and also type the object according to these options.

export default registerAs('database', () => {
  const config = {
    type: 'postgres',
    url: process.env.DATASOURCE_URL,
    autoLoadEntities: true,
  } as const satisfies TypeOrmModuleOptions;
  return config;
});

After that, we can substitute all that boilerplate code for simply this

TypeOrmModule.forRootAsync(databaseConfig.asProvider())

Commit - Reducing boilerplate in dynamic module configuration

Last updated