Using the variables

It's time to actually remove that data from the codebase and use it through environment variables.

Now, let's go back to the DatabaseModule and connect to the database in a different manner: asynchronously and using a factory. This means that, instead of already receiving the credentials directly in the code, it will await the environment variables to load in order to use them. Now we can also use just the URL, and have the following result

TypeOrmModule.forRootAsync({
  useFactory: () => ({
    type: 'postgres',
    url: process.env.DATASOURCE_URL,
    autoLoadEntities: true,
  }),
}),

Also, back in the file docker-compose.yml, let's use the password from the .env too.

POSTGRES_PASSWORD: ${DATASOURCE_PASSWORD}

And do the same with the port.

ports:
  - ${DATASOURCE_PORT}:5432

In the data-source file, unfortunately we'll need to use the packages dotenv and dotenv-expand directly, as it has no integration with Nest and, because of that, the ConfigModule can't be used here. We'll also need to write the imports manually because these packages are sub-dependencies, and as such will not benefit from code completion.

import * as dotenv from 'dotenv';
import * as dotenvExpand from 'dotenv-expand';

dotenvExpand.expand(dotenv.config());

export default new DataSource({
  // ...
  url: process.env.DATASOURCE_URL,
  // ...
});

Commit - Using environment variables

Last updated