Configuration namespace and partial registration

It would be nice to have some type safety for the environment variables.

There is still another interesting improvement we can make in the database connection. Notice that we are accessing the URL directly from process.env. Because of this, we cannot benefit from code completion and type safety. Fortunately, it is possible to store these variables in a type-safe manner through a configuration namespace.

Let's create one now, in the file database -> config -> database.config.

export default registerAs('database', () => ({
  url: process.env.DATASOURCE_URL,
}));

With this configuration namespace, we only need to access this variable directly from process.env once, in order to properly type it. Now, wherever it should be actually used, it can be accessed in a completely type-safe manner.

Now, we should perform the following steps inside the configuration of the TypeOrmModule in the DatabaseModule in order to use this namespace.

This is a very specific process, therefore it may be better to consider many of these steps as boilerplate instead of trying to understand them too deeply.

First, insert it in the imports array. After that, this set of variables will become available, but only here. This is called partial registration.

imports: [ConfigModule.forFeature(databaseConfig)],

Next, inject the KEY property of this namespace.

inject: [databaseConfig.KEY],

After that, insert as parameter of the factory, the object that actually has the typed field.

databaseConfiguration: ConfigType<typeof databaseConfig>,

After all the previous steps, we can now finally use a type-safe variable in the url field.

url: databaseConfiguration.url,

We should have the following result

TypeOrmModule.forRootAsync({
  imports: [ConfigModule.forFeature(databaseConfig)],
  inject: [databaseConfig.KEY],
  useFactory: (
    databaseConfiguration: ConfigType<typeof databaseConfig>,
  ) => ({
    type: 'postgres',
    url: databaseConfiguration.url,
    autoLoadEntities: true,
  }),  
}),

Commit - Using configuration namespace and partial registration

Last updated