ssun3
6/1/2019 - 8:52 PM

Nest Database Module (Type ORM) with environment variables support

Nest Database Module (Type ORM) with environment variables support

import { Module, Global, DynamicModule } from '@nestjs/common'
import { EnvModule } from './env.module'
import { EnvService } from './env.service'
import { TypeOrmModule } from '@nestjs/typeorm'

function DatabaseOrmModule (): DynamicModule {
  const config = new EnvService().read()

  return TypeOrmModule.forRoot({
    type: config.DB_TYPE,
    host: config.DB_HOST,
    port: config.DB_PORT,
    username: config.DB_USER,
    password: config.DB_PASSWORD,
    database: config.DB_NAME,

    synchronize: false
  })
}

@Global()
@Module({
  imports: [
    EnvModule,
    DatabaseOrmModule()
  ]
})
export class DatabaseModule { }
import { Module, Global } from '@nestjs/common'
import { EnvService } from './env.service'

@Global()
@Module({
  providers: [
    {
      provide: EnvService,
      useValue: new EnvService()
    }
  ],
  exports: [ EnvService ]
})
export class EnvModule {}
import * as dotenv from 'dotenv'
import * as fs from 'fs'

export interface EnvData {
  // application
  APP_ENV: string
  APP_DEBUG: boolean

  // database
  DB_TYPE: 'mysql' | 'mariadb'
  DB_HOST?: string
  DB_NAME: string
  DB_PORT?: number
  DB_USER: string
  DB_PASSWORD: string
}

export class EnvService {
  private vars: EnvData

  constructor () {
    const environment = process.env.NODE_ENV || 'development'
    const data: any = dotenv.parse(fs.readFileSync(`${environment}.env`))

    data.APP_ENV = environment
    data.APP_DEBUG = data.APP_DEBUG === 'true' ? true : false
    data.DB_PORT = parseInt(data.DB_PORT)

    this.vars = data as EnvData
  }

  read (): EnvData {
    return this.vars
  }

  isDev (): boolean {
    return (this.vars.APP_ENV === 'development')
  }

  isProd (): boolean {
    return (this.vars.APP_ENV === 'production')
  }
}
# Environment application template file

APP_DEBUG=false

# Database settings
DB_TYPE=mysql
DB_HOST=127.0.0.1
DB_NAME=mydb
DB_PORT=3306
DB_USER=root
DB_PASSWORD=root