Advertisement
metalni

typeorm

Aug 8th, 2022 (edited)
1,498
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { TypeOrmModuleOptions } from '@nestjs/typeorm'
  2. import { Logger, Injectable } from '@nestjs/common'
  3.  
  4. import { DataSource, DataSourceOptions } from 'typeorm'
  5.  
  6. @Injectable()
  7. class ConfigService {
  8.   private readonly logger = new Logger(ConfigService.name)
  9.  
  10.   constructor(private env: { [k: string]: string | undefined }) {}
  11.  
  12.   private getValue(key: string, throwOnMissing = true): string {
  13.     const value = this.env[key as string]
  14.     if (!value && throwOnMissing) {
  15.       throw new Error(`config error - missing env.${key}`)
  16.     }
  17.  
  18.     return value
  19.   }
  20.  
  21.   public ensureValues(keys: string[]) {
  22.     keys.forEach((k) => this.getValue(k, true))
  23.     return this
  24.   }
  25.  
  26.   public getPort() {
  27.     return this.getValue('PORT', true)
  28.   }
  29.  
  30.   public isProduction() {
  31.     const mode = this.getValue('MODE', false)
  32.     return mode != 'development'
  33.   }
  34.  
  35.   public getTypeOrmConfig(): TypeOrmModuleOptions {
  36.     return {
  37.       type: 'postgres',
  38.  
  39.       host: this.getValue('DB_HOST'),
  40.       port: parseInt(this.getValue('DB_PORT')),
  41.       username: this.getValue('DB_USER'),
  42.       password: this.getValue('DB_PASSWORD'),
  43.       database: this.getValue('DB_DATABASE'),
  44.  
  45.       migrationsTableName: 'migration',
  46.  
  47.       entities: ['src/models/**/*{.js,.ts}'],
  48.       migrations: ['src/database/migrations/**/*{.js,.ts}'],
  49.       subscribers: [
  50.         'src/subscribers/**/*{.js,.ts}',
  51.         'src/auth/subscribers/**/*{.js,.ts}',
  52.       ],
  53.  
  54.       ssl: false,
  55.     }
  56.   }
  57.  
  58.   public getDataSource(): DataSource {
  59.     return new DataSource({
  60.       ...(this.getTypeOrmConfig() as DataSourceOptions),
  61.     })
  62.   }
  63. }
  64.  
  65. const configService = new ConfigService(process.env).ensureValues([
  66.   'DB_HOST',
  67.   'DB_PORT',
  68.   'DB_USER',
  69.   'DB_PASSWORD',
  70.   'DB_DATABASE',
  71. ])
  72.  
  73. export { configService }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement