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

envrr

v0.1.4

Published

Nodejs Typescript Environment Validator and Loader

Downloads

5

Readme

envrr

Nodejs Typescript Environment Validator and Loader

Motivation

Tired of repeating (or copy/paste) the same environment variable handling and validation over and over again?
envrr aims to help with that!

It does so by using an Environment typed and decorated class via a small build step

Installing

npm install --save envrr

Setup

We start by firstly defining our env.ts

e.g.

// <cwd>/src/env.ts
import { EnvVariable, IsPartOfEnum, DefaultsTo, IsCronString } from 'envrr';

export class Environment {
  @EnvVariable('APPLICATION_NAME')
  applicationName: string;

  @EnvVariable('PORT')
  @DefaultsTo(3000)
  port: number;

  @EnvVariable('LOG_LEVEL')
  @IsPartOfEnum(['debug', 'info', 'warn', 'error'])
  logLevel: string;

  redis: RedisConnectionConfig;

  prometheus: PrometheusConfig;

  @EnvVariable('SECRET_EXPIRE_AT')
  secretExpireAt: Date;

  @EnvVariable('NOTIFY_PERIOD')
  @IsCronString()
  notifyPeriod: string;
}

class RedisConnectionConfig {
  @EnvVariable('REDIS_HOST')
  host: string;

  @EnvVariable('REDIS_PORT')
  port: number;

  @EnvVariable('REDIS_USERNAME')
  username: string;

  @EnvVariable('REDIS_PASSWORD')
  password: string;

  @EnvVariable('REDIS_INDEXES')
  indexes: string[];
}

class PrometheusConfig {
  @EnvVariable('PROMETHEUS_ENABLED')
  @DefaultsTo(false)
  enabled: boolean;

  @EnvVariable('PROMETHEUS_HOST')
  host: string;

  @EnvVariable('PROMETHEUS_PORT')
  port: number;

  @EnvVariable('PROMETHEUS_DEFAULT_QUANTILES')
  defaultQuantiles?: number[];

  flags?: PrometheusFlags;
}

class PrometheusFlags {
  @EnvVariable('PROMETHEUS_ENABLED_ENDPOINTS')
  enabledEndpoints?: string[];

  @EnvVariable('PROMETHEUS_ENABLED_USER_IDS')
  enabledUserIds?: number[];
}

Note: the name of the file nor the location is not important (as its target can be changed within the build step); the important part is to export the Environment class.

Building the env types

The type definition of the Environment class must be built in order to survive past runtime.
We use tparserr to translate the type definition into a .json file, and we do so as below:
tparserr generate --includeOnlyExports --enableDecorators -f=<env.ts target path> -o=<env.json output path>

By default envrr looks for the env.json type descriptions under <cwd>/env.json - this however can be changed via adjusting the targetPath passed to the envrr initialisation.

Following the example above, we can build the types by either manually running:
npx tparserr generate --includeOnlyExports --enableDecorators -f=./src/env.ts -o=./env.json
or simply adding it as a package.json script and hook it before out tsc build.

e.g.

{
  // ...
  "scripts": {
    "build-env": "tparserr generate --includeOnlyExports --enableDecorators -f=./src/env.ts -o=./env.json",
    "build": "npm run build-env && tsc"
  }
  // ...
}

Usage

It is recommended to initialise envrr as soon as possible during the app startup in order to validate if the whole environment corresponds to the typed Environment; after which it can be used/reused throughout the application without having to initialize (singleton).

// <cwd>/src/index.ts
process.env.APPLICATION_NAME = 'test';
process.env.PORT = '3000';
process.env.LOG_LEVEL = 'debug';

process.env.REDIS_HOST = 'localhost';
process.env.REDIS_PORT = '6379';
process.env.REDIS_USERNAME = 'user';
process.env.REDIS_PASSWORD = 'password';
process.env.REDIS_INDEXES = 'abc, def, ghi';

process.env.PROMETHEUS_ENABLED = 'true';
process.env.PROMETHEUS_HOST = 'localhost';
process.env.PROMETHEUS_PORT = '9090';
process.env.PROMETHEUS_DEFAULT_QUANTILES = '0.5, 0.9, 0.99';
process.env.SECRET_EXPIRE_AT = '2025-05-01 12:00:00';
process.env.NOTIFY_PERIOD = '* */1 * * *';

import { Environment } from './env';
import { Enver } from 'envrr';

(async function main() {
  await Enver.initialize<Environment>();

  const env = Enver.getEnv<Environment>();
  // const env: Environment

  const port = Enver.get<Environment, 'port'>('port');
  // const port: number

  const hasRedisHost = Enver.has('redis.host');
  // const hasRedisHost: boolean

  const redisOpts = Enver.get<Environment, 'redis'>('redis');
  // const redisOpts: RedisConnectionConfig

  const redisPort = Enver.get<Environment, 'redis', 'port'>('redis', 'port');
  // const redisPort: number

  const prometheusDefaultQuantiles = Enver.get<
    Environment,
    'prometheus',
    'defaultQuantiles'
  >('prometheus', 'defaultQuantiles');
  // const prometheusDefaultQuantiles: number[]

  const prometheusEnabledUserIds = Enver.get<
    Environment,
    'prometheus',
    'flags',
    'enabledUserIds'
  >('prometheus', 'flags', 'enabledUserIds');
  // const prometheusEnabledUserIds: number[]

  const secretExpireAt = Enver.get<Environment, 'secretExpireAt'>(
    'secretExpireAt'
  );
  // const secretExpireAt: Date
})().catch(console.error);

Note: in case the environment is invalid, envrr will throw errors in the order of validation/type description (fail-fast)

API tldr;

  • initialize - used to initialise envrr
  • getEnv - used to get the whole loaded environment
  • has - checks whether a json path (e.g. nesting.key.otherKey) to an environment variable exists
  • get - used to get specific env variable values

Supported Decorators

  • @EnvVariable - required on any Environment property that requires validation/loading
  • @IsPartOfEnum - used to restrict allowed values to a predefined enum
  • @DefaultsTo - used to default env variables if not present
  • @IsCronString - validates the string to be an either 5 char or 6 char cron string

Configuration

export interface IEnverConfig {
  // by default it points to <cwd>/env.json for its' to be loaded type definitions
  targetPath?: string;
}

Suggestions

Any improvement ideas/suggestions; feel free to open an issue :)

License

This library is licensed under the Apache 2.0 License