npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nestpack/config

v0.1.2

Published

Config module for NestJs projects

Downloads

3

Readme

Build Status

NestPack Config

A reusable Configuration Module for NestJs.

Features:

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

Installation

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

Basic Usage

Try it out on codesandbox (You may need to restart the sandbox on changes.)

# development.env
TEST_VAR= It worked!!
// 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 {}
// 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.

//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

// 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 {}
# development.env
VAR_THREE=3

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

// 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:

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.