Skip to content

Instantly share code, notes, and snippets.

@evanshortiss
Last active October 14, 2021 16:30
Show Gist options
  • Save evanshortiss/0cb049bf676b6138d13384671dad750d to your computer and use it in GitHub Desktop.
Save evanshortiss/0cb049bf676b6138d13384671dad750d to your computer and use it in GitHub Desktop.
Example code running without env-var. This is how you might implement env.get(MAX_BATCH_SIZE).required().asIntPositive()
/**
* All the assertion code below the line could be replaced with
* this single line by using env-var
*/
env.get(MAX_BATCH_SIZE).required().asIntPositive()
// -----------------------------------------------
const assert = require('assert');
// Our program requires this var to be set
assert.notEqual(
process.env.MAX_BATCH_SIZE,
undefined,
'MAX_BATCH_SIZE environment variable must be set'
);
// Read the var, and use parseInt to make it a number
const MAX_BATCH_SIZE = parseInt(process.env.MAX_BATCH_SIZE, 10);
// Verify we have a valid number, if not throw
assert(
typeof MAX_BATCH_SIZE === 'number' && !isNaN(MAX_BATCH_SIZE),
'MAX_BATCH_SIZE env var must be a valid number'
);
// Verify the number is positive
assert(
MAX_BATCH_SIZE > 0,
'MAX_BATCH_SIZE must be a positive number'
);
@mick62
Copy link

mick62 commented Jan 28, 2021

To achieve "fail early" all environment variables should be checked right on program start-up. All problems (not just the first one) should be included in the error message.

@evanshortiss
Copy link
Author

Feel free to start a discussion in the module repo if you'd like to contribute.

@evanshortiss
Copy link
Author

evanshortiss commented Jan 28, 2021

Here's an example of what I usually do, and recommend others do:

'use strict';

import { get } from 'env-var';

const config = {
  NODE_ENV: get('NODE_ENV').default('dev').asEnum(['dev', 'prod']),
  LOG_LEVEL: get('LOG_LEVEL').asString(),
};

export = config;

This solves your issue if you load it early in program execution (since you centralise reading the variables in one step). Hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment