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-zod-config

v2.4.0

Published

NestJS module to load, type and validate configuration using Zod

Downloads

258

Readme

NestJS Zod Config

NPM version NPM downloads Fastify

nestjs-zod-config - NestJS module to load, type and validate configuration using Zod. Insied and outside the NestJS context.

Installation

yarn add nestjs-zod-config

Peer dependencies: yarn add @nestjs/common zod

Setup

The first thing that we need to do is to create a config class that extends ZodConfig and pass it our Zod schema.

// app.config.ts
import { ZodConfig } from 'nestjs-zod-config';
import { z } from 'zod';

const appConfigSchema = z.object({
   HOSTNAME: z.string().min(1).default('0.0.0.0'),
   PORT: z.coerce.number().default(3000),
});

export class AppConfig extends ZodConfig(appConfigSchema) {}

This assumes that you have a .env file in the root of your project or that you have set the environment variables in process.env in some other way.

✨ All done. Let's see how we can use it.

Then we need to register the config class in our module.

Usage

Inside NestJS context

We will have to register the config class in a module:

// app.module.ts
import { Module } from '@nestjs/common';
import { ZodConfigModule } from 'nestjs-zod-config';
import { AppConfig } from './app.config';

@Module({
   imports: [
     ZodConfigModule.forRoot({
       config: AppConfig,
       isGlobal: true, // optional, defaults to `false`
     }),
   ],
})
export class AppModule {}

It is recommended to register the config class in the root module of your application.

Now we can inject AppConfig in your services like this:

// app.service.ts
import { Injectable } from '@nestjs/common';
import { AppConfig } from './app.config';

@Injectable()
export class AppService {
   constructor(private readonly appConfig: AppConfig) {}
   
   getPort(): number {
     return this.appConfig.get('PORT');
   }
}

or in our main.ts, like this:

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppConfig } from './app.config';
import { AppModule } from './app.module';

const main = async () => {
  const app = await NestFactory.create(AppModule);

  const appConfig = app.get(AppConfig);

  const hostname = appConfig.get('HOSTNAME');
  const port = appConfig.get('PORT');

  await app.listen(port, hostname);
};

void main();

Outside NestJS context

There are cases where we need to access the config outside the NestJS context. For example, we might want to use the config in a seeder script:

// seed.ts
import { loadZodConfig } from 'nestjs-zod-config';

const seedDb = async () => {
  const appConfig = loadZodConfig(AppConfig);

  const databaseurl = appConfig.get('DATABASE_URL');
  
  // use the `databaseurl` to connect to the database and seed it
};

In this case we cannot inject the AppConfig and we don't have access to the app instance. The file is executed outside the NestJS context.

Testing

yarn test

Roadmap

  • [ ] Provide a way to customize the env loader. Useful when different name, format or location of the env file is needed.
  • [ ] Provide async methods to load the config.
  • [ ] Write tests 🧪

Tips and Tricks

Use safeBooleanCoerce to coerce strings to booleans safely

This is a utility function that can be used to coerce a string value to a boolean in a strict manner.

Normally you will do: z.coerce.boolean() but this will also coerce the string 'false' to true. So instead we use this function to only allow 'false' or false to be coerced to false, 'true' or true to true and everything else will throw an error.