npm package: @nestpack/config
Description: Config module for NestJs projects
Author: Harry Horton
Latest version: 0.1.2

[![Build Status](https://github.com/NestPack/config/workflows/tests/badge.svg)](https://github.com/NestPack/config/actions)

# NestPack Config

A reusable Configuration Module for NestJs.

**Features**:

- .env file support
- programmatic overrides and defaults
- process.env support
- constants autogeneration

## Installation

```bash
$ npm install @nestpack/config
# OR
$ yarn add @nestpack/config
```

## Basic Usage

Try it out [on codesandbox](https://codesandbox.io/s/nestpack-config-example-453n4) (You may need to restart the sandbox on changes.)

```env
# development.env
TEST_VAR= It worked!!

```

```typescript
// app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';

// Import the config module
import { ConfigModule } from '@nestpack/config';

@Module({
  imports: [
    // register the config module in the module root.
    ConfigModule.register(),
  ],
  controllers: [AppController],
})
export class AppModule {}
```

```typescript
// app.controller.ts
import { Controller, Get } from '@nestjs/common';

// Import the ConfigService
import { ConfigService } from '@nestpack/config';

@Controller()
export class AppController {
  // Inject the ConfigService
  constructor(private readonly configService: ConfigService) {}

  @Get()
  getHello(): string {
    // get the desired config variable
    this.configService.get('TEST_VAR'); // returns "It worked!!"
  }
}
```

## How it Works

On application start, the `ConfigModule` will load either `[environment].env` or `development.env`(as a fallback). If no `.env` file exists, then none will be loaded.

When accessing variables through `ConfigService.get()`, the service will attempt to load variables in the order of:

- `overrides` from options
- `process.env`
- `.env` file variables
- `defaults` from options

## Overrides and Defaults

In the `ConfigModule` options object, `overrides` and `defaults` can be provided to include variables programatically.

```typescript
//app.module.ts
/* excluded imports */

@Module({
  imports: [
    ConfigModule.register({
      //Defaults can be used as a fallback if an environmental variable is not set.
      defaults: {
        FROM_DEV_ENV: 'default will be used if not defined anywher else',
        WILL_BE_OVERRIDDEN: 'Value will not be used',
      },

      // Overrides can be used to programmatically override any variable.
      overrides: {
        WILL_BE_OVERRIDDEN: 'Value used',
      },
    }),
  ],
  controllers: [AppController],
})
export class AppModule {}
```

## Constants generation

Since Nest is developed in a Typescript context, it's useful to include constants for accessing string based values by name. The `ConfigModule` can optionally generate a constants file to be used in the project. Constants are generated by combining the `.env` file, `overrides`, and `defaults` when the application loads. If a new environmental option has bene set somewhere, simply reload the application to regenerate the file. Note that a file will not be generated if the options haven't changed, as to not trigger a `tsc --watch` reload.

### Constants Usage

```typescript
// app.module.ts
/* excluded imports */

@Module({
  imports: [
    ConfigModule.register({
      // Add this option to generate a constants file
      generateConstants: true,

      // OPTIONAL if you want to output the constants file to another directory.
      // Default is src/
      constantsOutputDir: path.resolve(__dirname, './cosntants/'),

      // OPTIONAL if you want to only generate constants in specific environments.
      // Default is ['development', undefined]. undefined for no process.env.NODE_ENV set.
      generateConstantsEnviroments: ['development', 'test'],

      defaults: {
        VAR_ONE: '1',
      },

      overrides: {
        VAR_TWO: '2',
      },
    }),
  ],
  controllers: [AppController],
})
export class AppModule {}
```

```env
# development.env
VAR_THREE=3
```

When the application loads, it will generate a constants file like this:

```typescript
// src/constants.config.ts

export const CONFIG = {
  VAR_ONE: 'VAR_ONE',
  VAR_TWO: 'VAR_TWO',
  VAR_THREE: 'VAR_THREE',
};
```

With the constants file in place, the keys can be accessed through a reference:

```typescript
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from '@nestpack/config';
import { CONFIG } from './config.constants';

@Controller()
export class AppController {
  constructor(private readonly configService: ConfigService) {}

  @Get()
  getHello(): string {
    return this.configService.get(CONFIG.VAR_ONE); // returns "1"
  }
}
```

## Common Problems

### Using outside of module system

For injecting settings into setup functions or dynamic modules at application start, the module system is not yet available to provide `ConfigService`.

To solve this problem, simply call `new ConfigService()` anywhere in your project, and you can get environmental variables the same way. This is useful for setup steps like setting up the database.

Be aware that you shouldn't pass options to generate constants here, or else that functionality will run each time the service is initialized.

### NPM/Yarn Link

When using this package with NPM link, the `projectRoot` option will need to be set as the package cannot automatically determine the location under that scenario.

### process.env constants

The constants generation does not look at `process.env` because there are too many variables to take into account. If an environmental variable will only ever be set by the process environment, consider adding an empty default.

## License

[MIT licensed](LICENSE).