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

@applifting-io/nestjs-decorated-config

v1.0.2

Published

Nest.js config module with validation using class-validator decorators

Downloads

2,114

Readme

NestJS Decorated Config

Description

Environment variable configuration module for Nest.js featuring validation using class-validator decorators.

Installation

$ npm i @applifting-io/nest-decorated-config

Usage

Let's say you have the following .env file (or start your application in an environment providing those variables)

SECRET="WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE="
URL="http://localhost:3000"

ConfigService definition

Create your own ConfigService. Define a property for each environment variable. Decorate them with @Env decorator - make sure the first parameter matches your environment variable name.

Optionally decorate your properties with class-validator decorators.

// config.service.ts

import { Env } from '@applifting-io/nestjs-decorated-config';
import { Injectable } from '@nestjs/common';
import {
  IsNotEmpty,
  IsUrl,
} from 'class-validator';

@Injectable()
export class ConfigService {
  @Env('URL')
  @IsUrl()
  readonly url: string;

  @Env('SECRET')
  @IsNotEmpty()
  readonly secret: string;
}

Options

@Env optionally expects EnvDecoratorOptions as second parameter:

type EnvDecoratorOptions<T = any> = {
  /**
   * Variable's default value, used if no other value is populated from environment. Undefined by default
   */
  defaultValue?: T | (() => T);

  /**
   * Exposing will show the value of variable in log. False by default
   */
  expose?: boolean;

  /**
   * Removes last string character, if it is a forward slash. False by default
   */
  removeTrailingSlash?: boolean;

  /**
   * Parses the value to a JavaScript object with JSON.parse. Throws on invalid input. False by default
   */
  parseJson?: boolean;
};

ConfigModule initialization

Import and add ConfigModule to imports array of your root module.

// app.module.ts

import { ConfigModule } from '@applifting-io/nestjs-decorated-config';
import { Module } from '@nestjs/common';
import { ConfigService } from 'config.service.ts'

@Module({
  imports: [
    ConfigModule.forRootAsync(ConfigService)
  ]
})
export class AppModule {}

Options

ConfigModule.forRootAsync optionally expects ConfigModuleOptions as second parameter:

type ConfigModuleOptions = {
  /**
   * Print all variables with `expose: true`. False by default
   */
  printOnStartup?: boolean;
  /**
   * Validate all variables using class-validator decorators. True by default
   */
  validate?: boolean;
};

Inject ConfigService where needed

ConfigService is available globally, inject it like any other provider

// example.service.ts

@Injectable()
export class ExampleService {
  constructor(private readonly config: ConfigService) {}
  
  example() {
    console.log(config.url); // => 'http://localhost:3000'
    console.log(config.secret); // => 'WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE='
  }
}

Important

IMPORTANT If using .env files: Env decorators read environment variable values from process.env. Due to the nature of decorators in TS, you need to make sure variables from .env file are loaded into process.env before importing Env or any other JS module that itself imports Env.

One way to achieve this in practice is to run dotenv and then dynamically import the rest of your application in your main.ts entrypoint

// main.ts

import * as dotenv from 'dotenv';

// Dotenv needs to run before importing bootstrap, because @Env decorators are
// executed when JS interpreter interprets the decorated class which is in
// bootstrap's import tree, and we need env var resolution to be finished before that
dotenv.config();

import('./bootstrap').then(({ bootstrap }) => bootstrap());