Last active
October 14, 2021 16:30
-
-
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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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' | |
); |
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
Feel free to start a discussion in the module repo if you'd like to contribute.