1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
   |  import * as joi from 'joi'; import * as dotenv from 'dotenv'; import * as fs from 'fs';
 
  export interface EnvConfig {   [Key: string]: string; }
  export class ConfigService {   private readonly envConfig: EnvConfig;
    constructor(filePath: string) {     const config = dotenv.parse(fs.readFileSync(filePath));                this.envConfig = this.validateInput(config);                         }
    private validateInput(envConfig: EnvConfig): EnvConfig {     const envSchema: joi.ObjectSchema = joi.object({       DATABASE_NAME: joi.string()                         .valid(['blog', 'ablog'])                         .default('blog'),       DATABASE_USER: joi.string()                         .valid(['root', 'visitor'])                         .default('root'),       DATABASE_PASSWORD: joi.number().required()     });     const { error, value: validateConfig } = joi.validate(envConfig, envSchema);     if (error) {       throw new Error(error);     }     return validateConfig   }
       get databaseName(): string {     return this.envConfig.DATABASE_NAME;   }
    get databaseUser(): string {     return this.envConfig.DATABASE_USER;   }
    get databasePassword(): string {     return this.envConfig.DATABASE_PASSWORD;   } }
 
  |