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

@buka/nestjs-config

v2.1.6

Published

An easy to use nestjs config module

Downloads

22,929

Readme

@buka/nestjs-config

version downloads dependencies license Codecov

This is an easy-to-use nestjs config module with many surprising features.

Feature

  • Config verification by class-validator
  • Config transform by class-transformer
  • Load configuration files from anywhere
  • Perfect coding tips
  • Automatically handle naming styles
  • Injectable config class

Install

npm install @buka/nestjs-config
yarn install @buka/nestjs-config
pnpm install @buka/nestjs-config

Usage

@buka/nestjs-config load config from process.env and .env in process.cwd() by defaulted. let us create .env first:

# .env
CACHE_DIR="./tmp"
BROKERS="test01.test.com,test02.test.com,test03.test.com"

Then, define a AppConfig class with the @Configuration() decorator. And add decorators of class-validator to properties:

// app.config.ts
import { Configuration } from "@buka/nestjs-config";
import { IsString, IsOptional, IsIn, isIp } from "class-validator";
import { Split } from "@miaooo/class-transformer-split";

@Configuration()
export class AppConfig {
  // set default value
  @IsIp()
  host = "0.0.0.0";

  // CACHE_DIR in .env
  @IsString()
  @IsOptional()
  cacheDir?: string;

  // process.env.NODE_ENV
  @IsIn(["dev", "test", "prod"])
  nodeEnv: string;

  @Split(",")
  brokers: string[];
}

@buka/nestjs-config automatically convert naming styles. For example: cache_dirCACHE_DIRcacheDirCacheDircache-dirCache_Dir are considered to be the same config name.

Import ConfigModule in your AppModule:

// app.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule } from "@buka/nestjs-config";
import { AppConfig } from "./app.config";

@Module({
  // use process.env and read .env by defaulted
  imports: [
    ConfigModule.register({
      isGlobal: true,
      providers: [AppConfig],
    }),
  ],
})
export class AppModule {}

Inject and use AppConfig in your service:

import { Injectable } from "@nestjs/common";
import { AppConfig } from "./app.config";

@Injectable()
export class AppService {
  constructor(private readonly appConfig: AppConfig) {}
}

Add more dotenv files

import { Module } from "@nestjs/common";
import {
  ConfigModule,
  processEnvLoader,
  dotenvLoader,
} from "@buka/nestjs-config";
import { AppConfig } from "./app.config";

@Module({
  imports: [
    ConfigModule.register({
      isGlobal: true,
      providers: [AppConfig],
      loaders: [
        processEnvLoader,
        // transform DATABASE__HOST="0.0.0.0"
        // to DATABASE = { HOST: "0.0.0.0" }
        // transform LOG="true"
        // to LOG = true
        dotenvLoader(".env", { separator: "__", jsonParse: true }),
        dotenvLoader(`.${process.env.NODE_ENV}.env`),
      ],
    }),
  ],
})
export class AppModule {}

Custom config loader

// yaml-config-loader.ts
import { ConfigLoader } from "@buka/nestjs-config";
import { parse } from "yaml";

export async function yamlConfigLoader(filepath: string): ConfigLoader {
  return (options: ConfigModuleOptions) => {
    if (!existsSync(filepath)) {
      if (!options.suppressWarnings) {
        Logger.warn(`yaml file not found: ${filepath}`);
      }

      return {};
    }

    const content = await readFile(filepath);
    return parse(content);
  };
}

Use yamlConfigLoader:

import { Module } from "@nestjs/common";
import { ConfigModule } from "@buka/nestjs-config";
import { AppConfig } from "./app.config";
import { yamlConfigLoader } from "./yamlConfigLoader";

@Module({
  imports: [
    ConfigModule.register({
      isGlobal: true,
      providers: [AppConfig],
      loaders: [yamlConfigLoader("my-yaml-config.yaml")],
    }),
  ],
})
export class AppModule {}

Add prefix to all class properties

// mysql.config.ts
import { Configuration } from "@buka/nestjs-config";
import { IsString } from "class-validator";

@Configuration("mysql.master")
export class MysqlConfig {
  // process : process.env.MYSQL__MASTER__HOST
  // .env    : MYSQL__MASTER__HOST
  // .json   : { mysql: { master: { host: "" } } }
  @IsString()
  host: string;
}

Custom the config name of property

// app.config.ts
import { Configuration, ConfigName } from "@buka/nestjs-config";
import { IsString } from "class-validator";

@Configuration("mysql.master")
export class MysqlConfig {
  // process : process.env.DATABASE_HOST
  // .env    : DATABASE_HOST
  // .json   : { databaseHost: "" }
  @ConfigName("DATABASE_HOST")
  @IsString()
  host: string;
}

@ConfigName(name) will overwrite the prefix of @Configuration([prefix])

Remove warning logs

import { Module } from "@nestjs/common";
import { ConfigModule } from "@buka/nestjs-config";
import { AppConfig } from "./app.config";

@Module({
  imports: [
    ConfigModule.register({
      isGlobal: true,
      suppressWarnings: true,
      providers: [AppConfig],
    }),
  ],
})
export class AppModule {}

ConfigModule.inject(ConfigProvider, DynamicModule[, dynamicModuleOptions])

Simplify the writing of .forRootAsync/.registerAsync.

import { Module } from "@nestjs/common";
import { ConfigModule } from "@buka/nestjs-config";
import { KafkaModule, KafkaModuleOptions } from "@buka/nestjs-kafka";
import { AppConfig } from "./app.config";
import { KafkaConfig } from "./kafka.config";

@Module({
  imports: [
    ConfigModule.register({
      isGlobal: true,
      providers: [AppConfig, KafkaConfig],
    }),

    ConfigModule.inject(KafkaConfig, KafkaModule, { name: "my-kafka" }),
    // this is equal to
    KafkaModule.forRootAsync({
      name: "my-kafka",
      inject: [KafkaConfig],
      useFactory: (config: KafkaModuleOptions) => config,
    }),

    // Mapping KafkaConfig to options of KafkaModule manually
    ConfigModule.inject(
      KafkaConfig,
      KafkaModule,
      // override asyncOptions of KafkaModule
      { name: "my-kafka" },
      // override options of KafkaModule
      (config: KafkaConfig) => ({
        ...config,
        groupId: `prefix_${config.groupId}`,
      })
    ),

    // if you don't need override asyncOptions
    ConfigModule.inject(KafkaConfig, KafkaModule, (config: KafkaConfig) => ({
      ...config,
      groupId: `prefix_${config.groupId}`,
    })),
  ],
})
export class AppModule {}

Preload Config

Sometimes, we have to get config outside the nestjs lifecycle. ConfigModule.preload(options) is designed for this.

There is an example of MikroORM config file:

// mikro-orm.config.ts
import { ConfigModule } from "@buka/nestjs-config";
import { MySqlDriver, defineConfig } from "@mikro-orm/mysql";
import { MysqlConfig } from "./config/mysql.config";
import { Migrator } from "@mikro-orm/migrations";
import { BadRequestException } from "@nestjs/common";

export default (async function loadConfig() {
  // Load MysqlConfig
  await ConfigModule.preload({
    providers: [MysqlConfig],
  });

  // Get MysqlConfig Instance
  const config = await ConfigModule.get(MysqlConfig);

  return defineConfig({
    ...config,
    entities: ["dist/**/*.entity.js"],
    driver: MySqlDriver,
  });
})();

[!TIP]

The options of ConfigModule.preload(options) is the options of ConfigModule.register(options)