It is recommended to use the nestjs-config module in a NestJS project to get the configuration.

Nestjs-config provides the config.get() function, which reads the configuration via config.get(‘app.host’).

Nestjs-config: github.com/nestjs-comm…

Best practices

Access to the configuration

In general, there are the following ways to get configuration in a program:

  1. Hard code, write straight to death. – ❌ has low maintainability
  2. Write to ts files, such as config/app.ts. – ❌ Cannot be configured in different environments
  3. Read. Env directly. – ❌ is not recommended although it solves the problem of environment variables
  4. Environment variables are stored in.env, and configuration information is stored in ts files, which are then read using the config.get() function. – ✅ best practices

Coding standards

The general rule here is that all program configuration information must be read through config.get(), and environment variables must never be read outside of the configuration file.

Design concept

This has the following advantages:

  1. Config.get () reads configuration information. The. Env file stores environment variables and can be configured differently in different environments.
  2. Code robustness: Config.get () adds an abstraction layer on top of the.env file, making code more robust and flexible.

nestjs-config

Introducing way

// app.module.ts loads the configuration file in the config folder

import { ConfigModule } from 'nestjs-config'
// Note that the path here points to the config folder where the configuration files are stored
ConfigModule.load(path.resolve(__dirname, '.. '.'config'.'* * /! (*.d).{ts,js}')),
Copy the code

Use the sample

  1. The env fileUsed to configure all kinds of online sensitive data and server customized data, such as database passwords, secret keys, server IP, etc
  2. Environment variables in env files are read from dotenv library and formatted to encapsulate into general methods
  // env-unit.ts
  import * as dotenv from 'dotenv'
  
  dotenv.config()
  
  /** * formatting environment variables * @param key key value of environment variables * @param defaultValue defaultValue * @param callback formatting function */
  const fromatValue = <T>(key: string, defaultValue: T, callback: (value: string) => T) :T= > {
      const value: string | undefined = process.env[key]
      if (typeof value === 'undefined') {
          return defaultValue
      }
      return callback(value)
  }
  
  export const env = (key: string, defaultValue: string= ' ') = > fromatValue(key, defaultValue, value= > value)
  
  export const envNumber = (key: string, defaultValue: number = 0) = > fromatValue(key, defaultValue, value= > Number(value))
  
  export const envBoolean = (key: string, defaultValue: boolean = false) = > fromatValue(key, defaultValue, value= > value === 'true')
Copy the code
  1. Create app.ts in config folder and read by using env(), envNumber(), envBoolean(). Env and format the configuration, with the second parameter set to default
// config/app.ts
export {
  port: envNumber('APP_PORT'.3000)}Copy the code
  1. Config is used in the service through dependency injection
import {InjectConfig} from 'nestjs-config'; @InjectConfig() class SomeService {constructor(@InjectConfig() private readonly config) {} getAppHost() {// Use string add. Return this.config.get('app.port')}}Copy the code