Generating database url in codebase

A potentially more robust way to generate the database url.

We have successfully adopted the usage of environment variables in this section. However, we are creating the database url from the credentials directly in the .env file. We could also do so in the codebase, avoiding the need to have it inside .env. This would also allow for a more concise setup when deploying the application.

First, we should remove this variable from .env and .env.example. After that, we can also remove it from the validation schema in the env.constants file, and even remove the expandVariables option from the ConfigModule configuration in the EnvModule, as we're no longer using it.

Then, inside the database.config file, we should extract all the credentials from the .env file and then create the url from it. Finally, use it in the config.

const user = process.env.DATABASE_USER;
const password = process.env.DATABASE_PASSWORD;
const host = process.env.DATABASE_HOST;
const port = process.env.DATABASE_PORT;
const name = process.env.DATABASE_NAME;

const url = `postgresql://${user}:${password}@${host}:${port}/${name}`;

const config = {
  // ...
  url,
  // ...
} as const satisfies TypeOrmModuleOptions;

Remember to do the same in the data-source file.

Commit - Generating database url in codebase

Last updated