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

nestjs-safer-config

v0.11.0

Published

The `SaferConfigModule` allows to define and load multiple configuration from any source you want: plain object, yaml file, json file, toml file, or any other parsable format, or from HTTP json response.

Downloads

117

Readme

Configuration module for NestJS

The SaferConfigModule allows to define and load multiple configuration from any source you want: plain object, yaml file, json file, toml file, or any other parsable format, or from HTTP json response.

You can manage complex configuration object hierarchies.

Motivation

I wanted config module for NestJS to be:

  • easy to use
  • type-safe
  • reliable
  • explains when something goes wrong
  • suitable for need of current project

And I made it.

Trade-offs

  1. The main purpose of using class-validator and class-transformer packages is to allow developers to inject configuration object as a dependency using standard and simplest constructor injection in a type-safe way. One more advantage of using packages mentioned above is that they widely knew and used by default in NestJS projects. The disadvantage is that decorators might be not the best way to describe expectations. For example, it is crucial to not forget to add @ValidateNested() if you need to validate nested instances. Or it is required to add @Type(() => Number) if you want to apply string-to-number transformations for a field. Perhaps the biggest disadvantage is that at this moment the class-validator and class-transformer packages have little support. Little support from reach companies which makes money on open-source and a little support from package owners.
  2. @nestjs/config have registerAs method. With this kind of API there is no way to achieve type-safety, so, there is no such feature in nestjs-safer-config package.

Prerequisites

Peer dependencies:

{
  "@nestjs/common": "^9.2.1",
  "class-transformer": "^0.5.1",
  "class-validator": "^0.14.0",
  "reflect-metadata": "^0.1.13"
}

WARNING: if your project does not use these packages. The nestjs-safer-config package is not for you.

How to use

Install

npm i nestjs-safer-config

Define a config class

  1. Describe how config should look like using class declaration statement. And decorate fields with class-validator decorators. For example,

    class AppConfig {
      @IsString()
      SECRET_PHRASE: string;
    
      @IsIn(["development", "qa", "stage", "production"])
      stage: string = "development"; // here you can use the default values, they are the lowest priority
    
      @IsPort() // @IsPort() checks if the value is a string and is a valid port number.
      port: string = "3000";
    }

    NOTE: I strongly recommend to add readonly modifier to all and each fields

Import SaferConfigModule

  1. Import SaferConfigModule in the following way:

    @Module({
      imports: [
        SaferConfigModule.register({
          isGlobal: true, // or false, or you can skip `isGlobal`
          createInstanceOf: AppConfig, // will be instantiated with data from `sources`. Should not have a `constructor` defined, or `constructor` shouldn't expect any arguments
          sources: [
            // `sources` must be an array of objects or promises of objects
            // `sources` will be merged into one object with `Object.assign()`. That object will be used to populate `AppConfig` properties
            // in this example let's use one object
            process.env,
          ],
        }),
      ],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}

Specify AppConfig as dependency in a constructor of an injectable service

  1. Use the config class identifier as NestJS provider token

    • for example, here how it can be injected in AppService

      @Injectable()
      export class AppService {
        constructor(private readonly appConfig: AppConfig) {}
      
        getHello(): string {
          return `Hello World! Here is my secret '${this.appConfig.SECRET_PHRASE}'`;
        }
      }
    • or in main.ts

      async function bootstrap() {
        const app = await NestFactory.create(AppModule);
        const cfg = app.get(AppConfig);
        await app.listen(cfg.port);
      }
      bootstrap();
  2. Start your app with environment variables defined:

    SECRET_PHRASE='somesecret' stage=stage port=8080 node ./dist/main.js

How to read .env file

Use parse-dotenv-file package.

import { tryParseDotenvFile } from "parse-dotenv-file";

@Module({
  imports: [
    SaferConfigModule.register({
      isGlobal: true,
      createInstanceOf: AppConfig,
      sources: [
        // `sources` will be merged into one object with `Object.assign()`. That object will be used to populate `AppConfig` properties
        tryParseDotenvFile(),
        process.env,
      ],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

HTTP source

What if you want to use secrets from env vars to fetch secrets over HTTP? Use SaferConfigModule.registerAsync static method.

import { SaferConfigModule } from "nestjs-safer-config";

class EnvVarSecrets {
  @IsString()
  token: string;
}

const envVarsSecretsModule = SaferConfigModule.register({
  createInstanceOf: EnvVarSecrets,
  sources: [process.env],
});

const secretsFetchWithHttpModule = SaferConfigModule.registerAsync({
  imports: [envVarsSecretsModule],
  isGlobal: true,
  createInstalceOf: AppConfig,
  inject: [EnvVarSecrets],
  sourcesFactory: async (envVarSecrets: EnvVarSecrets) => {
    const url = "https://example.com/secrets";
    return await fetchSecretsViaHttp(url, envVarSecrets.token);
  },
});

@Module({
  imports: [secretsFetchWithHttpModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}