@spine/env-vars

0.0.2 • Public • Published

Spine Env Vars Utility

An utility to find and cast environment to Javascript types

How to use

import { EnvVars } from '@spine/env-vars';

const envVars = new EnvVars();

export default {
   listenPort: envVars.int('LISTEN_PORT', 3000),
   listenAddress: envVars.string('LISTEN_ADDRESS', 'localhost'),
   secure: {
     enabled: envVars.bool('SECURE_ENABLED', false),
     certKey: envVars.value('SECURE_CERT_KEY'),
     privateKey: envVars.value('SECURE_PRIVATE_KEY'),
   },
   someJSONConfig: envVars.json('MY_CONFIG', {}),
};

Casting processes

envVars.value

Returns the original string value

envVars.string

Perform a trim and remove initial and final double quotes, if it's empty returns default value

envVars.number

Execute envVars.string() and after cast with Number() if strict, if not strict it uses parseFloat, and if it is NaN returns default value

envVars.int

Execute envVars.number() and after truncates to integer (if not strict)

envVars.bool

Execute envVars.string() and after matches for a boolean value, the following is accepted...

true false
1 0
t f
on off
enable disable
enabled disabled

Otherwise returns default value

envVars.json

Parses environment as JSON, and in case of an error returns default value

Throw or Log Cast Error

Cast errors are silent by default, in case of a cast error it just returns the default value.

You can change this behavior by specifying the throwOrLogCastError property.

envVars.throwOrLogCastError = error => throw error;

or simply log it, without breaking name matches or preventing default from returning.

envVars.throwOrLogCastError = (error, name, type, value) => {
  console.log(`Env "${name}" does not represent a valid ${type}.`);
};

Strict Cast Numbers

If set to false it will use parseInt() and parseFloat() instead of Number() to cast numbers.

process.env.LISTEN_PORT = '80whatever';
envVars.int('LISTEN_PORT', 3000);
// Returns 3000
envVars.strictCastNumber = false;
envVars.int('LISTEN_PORT', 3000);
// Returns 80

Cast Error Break Matches

If set to false and cast errors are not being thrown it will try to cast the next environment name.

envVars.castErrorBreakMatches = false;
process.env.LISTEN_PORT = 'invalid number';
process.env.HTTP_LISTEN_PORT = '80';
envVars.int(['LISTEN_PORT', 'HTTP_LISTEN_PORT'], 3000);
// Returns 80

Package Sidebar

Install

npm i @spine/env-vars

Weekly Downloads

0

Version

0.0.2

License

MIT

Unpacked Size

35.1 kB

Total Files

8

Last publish

Collaborators

  • ezsper