Nx NestJs - Typeorm database connection with environment variables
Tags: javascript, webdev, tutorial, nestjs
Published: 2022-05-09 22:34:49

Continuing from the last article, we should already have a defined ConfigModule and environment variables.

To set up the data base connection in this case it's just a matter of a few lines of code.
In my example I will use a Postgresql database, but it can be any type of database. 
- Install the `npm install --save @nestjs/typeorm typeorm@0.3 pg`. `pg` is the Postgresql driver used by Typeorm to connect to the database. For each individual database it will be a different driver, e.g. `sql2`, `mongoose` and others. The typeorm we installed is v0.3, in the nestJs documentation it is recommended to use the v0.2 but it's compatible and newer, If you dislike it you can use v0.2. 
- Create in the project's folder a `typeorm` folder with a `typeorm.service.ts` file.
- Add to the file the following:
```ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';

import { IEnvironment } from './../environments/env.interface';

@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
  constructor(private config: ConfigService) {}

  public createTypeOrmOptions(): TypeOrmModuleOptions {
    const db = this.config.get<IEnvironment['database']>('database') as IEnvironment['database'];
    const productionMode = this.config.get<IEnvironment['production']>('production') as IEnvironment['production'];
    return {
      type: 'postgres',
      host: db.host,
      port: db.port,
      database: db.database,
      username: db.username,
      password: db.password,
      //   migrations: ['dist/migrations/*.{ts,js}'],
      logger: 'file',
      synchronize: !productionMode, // never use TRUE in production!
      autoLoadEntities: true,
    };
  }
}
```

Special mentions about this:
- migrations are disabled. We will come back to them in a different article because they are managed outside of Nx and NestJs using the TypeOrm Cli. 
- the synchronize is turned on only in non-production environment

Now all that it remained is to use this class in the AppModule(or a separate DatabaseModule if you would like to have a more granular approach)

- Go to `app.module.ts` and add in the imports `    TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService })`
For example, my app.module.ts looks like this
```ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

import { getEnvConfig } from './environments/env-config';
import { envValidation } from './environments/env-validator';
import { TypeOrmConfigService } from './typeorm/typeorm.service';

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [getEnvConfig],
      isGlobal: true,
      cache: true,
      validate: envValidation,
    }),
    TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService })
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
```

That was it, next step would be creating models and services. A good documentation about that is [here](https://docs.nestjs.com/techniques/database#repository-pattern)

Thanks for reading!