Comparing version 6.3.0 to 7.0.0
@@ -1,6 +0,11 @@ | ||
## 6.3.0 | ||
## 7.0.0 (11/11/2020) | ||
* Drop support for Node.js 8 and 13 (support only current, active, and maintenance versions) | ||
* Improve support for browser usage (#138) | ||
* Fix documentation errors (#139) | ||
## 6.3.0 (27/07/2020) | ||
* Add `asRegExp` accessor (#136) | ||
* Add better TypeScript example for custom accessors (#133) | ||
## 6.2.0 (12/06/20) | ||
## 6.2.0 (12/06/2020) | ||
* Add `accessors` property to the public API for use in building `extraAccessors` (#121) | ||
@@ -15,23 +20,23 @@ * Add support for logging with a built-in or custom logger (#112) | ||
## 6.1.1 (22/04/20) | ||
## 6.1.1 (22/04/2020) | ||
* Fix TS error with *ExtenderTypeOptional* and *ExtenderType* typings (#119) | ||
## 6.1.0 (20/04/20) | ||
## 6.1.0 (20/04/2020) | ||
* Fix TS error with *extraAccessor* typings (#114) | ||
* Add support for generic types in *asEnum* (#116) | ||
## 6.0.4 (04/03/20) | ||
## 6.0.4 (04/03/2020) | ||
* Fix compilation error caused by typings generic issue. | ||
## 6.0.3 (03/03/20) | ||
## 6.0.3 (03/03/2020) | ||
* Fix typings to support `required()`, `convertFromBase64()`, etc. with `ExtensionFn`. | ||
## 6.0.2 (29/02/20) | ||
## 6.0.2 (29/02/2020) | ||
* Fix `default()` so that it correctly returns an empty string value if provided. | ||
* README improvement by @joh-klein for positive/negative number parsing rules. | ||
## 6.0.1 (12/02/20) | ||
## 6.0.1 (12/02/2020) | ||
* Fix typings for the `default(value)` function. | ||
## 6.0.0 (12/02/20) | ||
## 6.0.0 (12/02/2020) | ||
* Add support for setting an example value via the `example(string)` function. | ||
@@ -54,6 +59,6 @@ * Passing default values is now performed using the `default(string)` function. | ||
## 5.2.0 (22/11/19) | ||
## 5.2.0 (22/11/2019) | ||
* The `required()` function now verifies the variable is not an empty string | ||
## 5.1.0 (09/09/19) | ||
## 5.1.0 (09/09/2019) | ||
* Ability to add custom accessors in PR #72 (thanks @todofixthis) | ||
@@ -63,3 +68,3 @@ * Improved TypeScript tests | ||
## 5.0.0 (14/06/19) | ||
## 5.0.0 (14/06/2019) | ||
* Return values from `asArray()` are now more intuitive & consitent | ||
@@ -70,10 +75,10 @@ * `asUrlString()` and `asUrlObject`now use the built-in `URL` class in Node.js | ||
## 4.1.0 (14/06/19) | ||
## 4.1.0 (14/06/2019) | ||
* Add `asPortNumber()` function | ||
* Update documentation structure | ||
## 4.0.1 (24/05/19) | ||
## 4.0.1 (24/05/2019) | ||
* Add node `process.env` typings to `env.from` | ||
## 4.0.0 (09/04/19) | ||
## 4.0.0 (09/04/2019) | ||
* Rename `.env.mock()` to `env.from()` | ||
@@ -83,32 +88,32 @@ * Change module internals per issue #39 | ||
## 3.5.0 (02/29/19) | ||
## 3.5.0 (02/29/2019) | ||
* Update `required()` to support boolean paramter to bypass the check | ||
## 3.4.2 (06/11/18) | ||
## 3.4.2 (06/11/2018) | ||
* Fix README badge copy/paste error | ||
## 3.4.1 (06/11/18) | ||
## 3.4.1 (06/11/2018) | ||
* Fix TypeScript definition for "asBoolStrict" function name | ||
## 3.4.0 (24/10/18) | ||
## 3.4.0 (24/10/2018) | ||
* Add `convertFromBase64()` function | ||
* Enable Greenkeeper | ||
## 3.3.0 (26/06/18) | ||
## 3.3.0 (26/06/2018) | ||
* Add `asEnum` functionality | ||
## 3.2.0 (15/06/18) | ||
## 3.2.0 (15/06/2018) | ||
* Remove @types/node dependency | ||
## 3.1.0 (11/12/17) | ||
## 3.1.0 (11/12/2017) | ||
* Update typings to correctly handle default values for numeric types. | ||
* Ensure an error is thrown when `asArray` does not detect at least a single non-empty value. | ||
## 3.0.2 (19/10/17) | ||
## 3.0.2 (19/10/2017) | ||
* Restore support for use in browser based applications | ||
## 3.0.1 (19/10/17) | ||
## 3.0.1 (19/10/2017) | ||
* Fix bug that caused default values to be ignored | ||
## 3.0.0 (13/10/17) | ||
## 3.0.0 (13/10/2017) | ||
* Public API no longer is a function, instead exposes two functions, `mock` and `get` | ||
@@ -124,3 +129,3 @@ * Drop support for Node.js versions less than 4.0 | ||
## 2.4.3 (5/04/17) | ||
## 2.4.3 (5/04/2017) | ||
* Update with build, coverage, and version information badges | ||
@@ -127,0 +132,0 @@ |
'use strict' | ||
const URL = require('url').URL | ||
const asString = require('./string') | ||
@@ -5,0 +4,0 @@ |
'use strict' | ||
const inherits = require('util').inherits | ||
/** | ||
* Creates a custom error class that can be used to identify errors generated | ||
* Custom error class that can be used to identify errors generated | ||
* by the module | ||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} | ||
*/ | ||
function EnvVarError (message) { | ||
Error.captureStackTrace(this, this.constructor) | ||
this.name = 'EnvVarError' | ||
this.message = `env-var: ${message}` | ||
}; | ||
class EnvVarError extends Error { | ||
constructor (message, ...params) { | ||
super(`env-var: ${message}`, ...params) | ||
/* istanbul ignore else */ | ||
if (Error.captureStackTrace) { | ||
Error.captureStackTrace(this, EnvVarError) | ||
} | ||
inherits(EnvVarError, Error) | ||
this.name = 'EnvVarError' | ||
} | ||
} | ||
module.exports = EnvVarError |
{ | ||
"name": "env-var", | ||
"version": "6.3.0", | ||
"version": "7.0.0", | ||
"description": "Verification, sanitization, and type coercion for environment variables in Node.js", | ||
@@ -62,11 +62,11 @@ "main": "env-var.js", | ||
"husky": "~4.2.2", | ||
"mocha": "~7.1.0", | ||
"mocha": "~8.2.0", | ||
"mocha-lcov-reporter": "~1.3.0", | ||
"nyc": "~15.0.0", | ||
"standard": "~14.3.0", | ||
"nyc": "~15.1.0", | ||
"standard": "~14.3.4", | ||
"typescript": "~3.8.3" | ||
}, | ||
"engines": { | ||
"node": ">=8" | ||
"node": ">=10" | ||
} | ||
} |
578
README.md
@@ -14,4 +14,3 @@ # env-var | ||
Verification, sanitization, and type coercion for environment variables in | ||
Node.js. Supports TypeScript! | ||
Verification, sanitization, and type coercion for environment variables in Node.js and web applications. Supports TypeScript! | ||
<br> | ||
@@ -22,25 +21,36 @@ <br> | ||
* 🏋 Lightweight. Zero dependencies and just ~4.7kB when minified! | ||
* 🧹 Cleaner code, as [shown here](https://gist.github.com/evanshortiss/0cb049bf676b6138d13384671dad750d) | ||
* 🚫 [Fail fast](https://en.wikipedia.org/wiki/Fail-fast) if your environment is misconfigured | ||
* 👩💻 Friendly error messages and example values improve developer experience | ||
* 🎉 TypeScript support provides compile time safety and better developer experience | ||
* 🧹 Clean and simple code, as [shown here](https://gist.github.com/evanshortiss/0cb049bf676b6138d13384671dad750d). | ||
* 🚫 [Fails fast](https://en.wikipedia.org/wiki/Fail-fast) if your environment is misconfigured. | ||
* 👩💻 Friendly error messages and example values for better debugging experience. | ||
* 🎉 TypeScript support provides compile time safety and better developer experience. | ||
* 📦 Support for frontend projects, e.g in React, React Native, Angular, etc. | ||
## Contents | ||
- [API](API.md): The full API set for `env-var` | ||
- [Changelog](CHANGELOG.md) | ||
- [Code of Conduct](CODE_OF_CONDUCT.md) | ||
- [Contributing](CONTRIBUTING.md) | ||
- [Examples](EXAMPLE.md): Example usage of `env-var` | ||
## Install | ||
**Note:** requires Node version 8 or later. | ||
### npm | ||
```shell | ||
npm install env-var | ||
``` | ||
npm install env-var --save | ||
``` | ||
### yarn | ||
``` | ||
```shell | ||
yarn add env-var | ||
``` | ||
## Usage | ||
In the example below we read the environment variable *DB_PASSWORD* and call | ||
some functions to verify it satisfies our program's needs. | ||
## Getting started | ||
You can use `env-var` in both JavaScript and TypeScript! | ||
### Javascript example | ||
```js | ||
@@ -65,3 +75,3 @@ const env = require('env-var'); | ||
## TypeScript | ||
### TypeScript example | ||
@@ -77,59 +87,22 @@ ```ts | ||
## Usage with dotenv | ||
For more examples, refer to the `/example` directory and [EXAMPLE.md](EXAMPLE.md). A summary of the examples available in `/example` is written in the ['Other examples' section of EXAMPLE.md](EXAMPLE.md#other-examples). | ||
There is no tight coupling between [env-var](https://www.npmjs.com/package/env-var) | ||
and [dotenv](https://www.npmjs.com/package/dotenv). Just `npm install dotenv` | ||
and use it whatever way you're used to. This loose coupling is a good thing | ||
since it reduces package bloat - only install what you need! | ||
## API | ||
You can use `dotenv` with `env-var` via a `require()` calls in your code or | ||
preloading it with the `--require` or `-r` flag in the `node` CLI. | ||
The examples above only cover a very small set of `env-var` API calls. There are many others such as `asFloatPositive()`, `asJson()` and `asRegExp()`. For a full list of `env-var` API calls, check out [API.md](API.md). | ||
Both examples below assume you have a `.env` file in your repository and it | ||
contains a line similar to `MY_VAR=a-string-value!`. | ||
You can also create your own custom accessor; refer to the ['extraAccessors' section of API.md](API.md#extraAccessors). | ||
### Load dotenv via require() | ||
This is per the default usage described by [dotenv's README](https://www.npmjs.com/package/dotenv#usage). | ||
```js | ||
// Read in the .env file | ||
require('dotenv').config() | ||
// Read the MY_VAR entry that dotenv created | ||
const env = require('env-var') | ||
const myVar = env.get('MY_VAR').asString() | ||
``` | ||
### Preload dotenv via CLI Args | ||
This is per the [preload section](https://www.npmjs.com/package/dotenv#preload) | ||
of the dotenv README. Run the following code by using the | ||
`node -r dotenv/config your_script.js` command. | ||
```js | ||
// This is just a regular node script, but we started it using the command | ||
// "node -r dotenv/config your_script.js" via the terminal. This tells node | ||
// to load our variables using dotenv before running the rest of our script! | ||
// Read the MY_VAR entry that dotenv created | ||
const env = require('env-var') | ||
const myVar = env.get('MY_VAR').asString() | ||
``` | ||
## Logging | ||
Logging is disabled by default in `env-var` to prevent accidentally logging | ||
secrets. | ||
Logging is disabled by default in `env-var` to prevent accidental logging of secrets. | ||
To enable logging you need to create an `env-var` instance using the `from()` | ||
function that the API provides and pass it a logger. A built-in logger is | ||
available, but a custom logger is also supported. | ||
To enable logging, you need to create an `env-var` instance using the `from()` function that the API provides and pass in a logger. | ||
Always exercise caution when logging environment variables! | ||
- A built-in logger is available, but a custom logger is also supported. | ||
- Always exercise caution when logging environment variables! | ||
### Using the Built-in Logger | ||
The built-in logger will print logs unless `NODE_ENV` is set to either `prod` | ||
or `production`. | ||
The built-in logger will print logs only when `NODE_ENV` is **not** set to either `prod` or `production`. | ||
@@ -143,4 +116,3 @@ ```js | ||
Here's output from the built-in logger that can be seen by running | ||
*examples/logging.js* included in this repository: | ||
This is an example output from the built-in logger generated by running [example/logging.js](example/logging.js): | ||
@@ -151,484 +123,20 @@ ![logging example output](screenshots/logging.png) | ||
If you're using a logging solution such as `pino` this feature is useful to | ||
filter logs based on log levels, e.g `env-var` logs can be enabled for trace | ||
logging only. | ||
If you need to filter `env-var` logs based on log levels (e.g. trace logging only) or have your own preferred logger, you can use a custom logging solution such as `pino` easily. | ||
```js | ||
const pino = require('pino')() | ||
const customLogger = (varname, str) => { | ||
// varname is the name of the variable being read, e.g "API_KEY" | ||
// str is the log message, e.g "verifying variable value is not empty" | ||
log.trace(`env-var log (${varname}): ${str}`) | ||
} | ||
See the ['Custom logging' section of EXAMPLE.md](EXAMPLE.md#custom-logging) for more information. | ||
const { from } = require('env-var') | ||
const env = from(process.env, {}, customLogger) | ||
## Optional integration with dotenv | ||
const API_KEY = env.get('API_KEY').required().asString() | ||
``` | ||
You can optionally use [dotenv](https://www.npmjs.com/package/dotenv) with [env-var](https://www.npmjs.com/package/env-var). | ||
There is no coupling between `dotenv` and `env-var`, but you can easily use them both together. This loose coupling reduces package bloat and allows you to start or stop using one without being forced to do the same for the other. | ||
## API | ||
See the ['dotenv' section of EXAMPLE.md](EXAMPLE.md#dotenv) for more information. | ||
### Structure: | ||
## Contributing | ||
* module (env-var) | ||
* [from()](#fromvalues-extraaccessors) | ||
* [get()](#getvarname) | ||
* [variable](#variable) | ||
* [required()](#requiredisrequired--true) | ||
* [covertFromBase64()](#convertfrombase64) | ||
* [example(string)](#examplestring) | ||
* [default(string)](#defaultstring) | ||
* [asArray()](#asarraydelimiter-string) | ||
* [asBoolStrict()](#asboolstrict) | ||
* [asBool()](#asbool) | ||
* [asPortNumer()](#asportnumber) | ||
* [asEnum()](#asenumvalidvalues-string) | ||
* [asFloatNegative()](#asfloatnegative) | ||
* [asFloatPositive()](#asfloatpositive) | ||
* [asFloat()](#asfloat) | ||
* [asIntNegative()](#asintnegative) | ||
* [asIntPositive()](#asintpositive) | ||
* [asInt()](#asint) | ||
* [asJsonArray()](#asjsonarray) | ||
* [asJsonObject()](#asjsonobject) | ||
* [asJson()](#asjson) | ||
* [asString()](#asstring) | ||
* [asUrlObject()](#asurlobject) | ||
* [asUrlString()](#asurlstring) | ||
* [asRegExp()](#asregexp) | ||
* [EnvVarError()](#envvarerror) | ||
* [accessors](#accessors) | ||
Contributions are welcomed and discussed in [CONTRIBUTING.md](CONTRIBUTING.md). If you would like to discuss an idea, open an issue or a PR with an initial implementation. | ||
### from(values, extraAccessors, logger) | ||
This function is useful if you're not in a typical Node.js environment, or for | ||
testing. It allows you to generate an `env-var` instance that reads from the | ||
given `values` instead of the default `process.env` Object. | ||
## Contributors | ||
```js | ||
const env = require('env-var').from({ | ||
API_BASE_URL: 'https://my.api.com/' | ||
}) | ||
// apiUrl will be 'https://my.api.com/' | ||
const apiUrl = env.get('API_BASE_URL').asUrlString() | ||
``` | ||
When calling `env.from()` you can also pass an optional parameter containing | ||
custom accessors that will be attached to any variables returned by that | ||
`env-var` instance. This feature is explained in the | ||
[extraAccessors section](#extraAccessors) of these docs. | ||
Logging can be enabled by passing a logger function that matches the signature: | ||
```js | ||
/** | ||
* Logs the provided string argument | ||
* @param {String} varname | ||
* @param {String} str | ||
*/ | ||
function yourLoggerFn (varname, str) { | ||
// varname is the name of the variable being read, e.g "API_KEY" | ||
// str is the log message, e.g "verifying variable value is not empty" | ||
} | ||
``` | ||
### get(varname) | ||
This function has two behaviours: | ||
1. Calling with a string argument will make it read that value from the environment | ||
2. If no string argument is passed it will return the entire environment object | ||
Examples: | ||
```js | ||
const env = require('env-var') | ||
// #1 - Read the requested variable and parse it to a positive integer | ||
const limit = env.get('MAX_CONNECTIONS').asIntPositive() | ||
// #2 - Returns the entire process.env object | ||
const allVars = env.get() | ||
``` | ||
### variable | ||
A variable is returned by calling `env.get(varname)`. It exposes the following | ||
functions to validate and access the underlying value, set a default, or set | ||
an example value: | ||
#### example(string) | ||
Allows a developer to provide an example of a valid value for the environment | ||
variable. If the variable is not set (and `required()` was called), or the | ||
variable is set incorrectly this will be included in error output to help | ||
developers diagnose the error. | ||
For example: | ||
```js | ||
const env = require('env-var') | ||
const ADMIN_EMAIL = env.get('ADMIN_EMAIL') | ||
.required() | ||
.example('admin@example.com') | ||
.asString() | ||
``` | ||
If *ADMIN_EMAIL* was not set this code would throw an error similar to that | ||
below to help a developer diagnose the issue: | ||
``` | ||
env-var: "ADMIN_EMAIL" is a required variable, but it was not set. An example | ||
of a valid value would be "admin@example.com" | ||
``` | ||
#### default(string) | ||
Allows a default value to be provided for use if the desired environment | ||
variable is not set in the program environment. | ||
Example: | ||
```js | ||
const env = require('env-var') | ||
// Use POOL_SIZE if set, else use a value of 10 | ||
const POOL_SIZE = env.get('POOL_SIZE').default('10').asIntPositive() | ||
``` | ||
#### required(isRequired = true) | ||
Ensure the variable is set on *process.env*. If the variable is not set, or is | ||
set to an empty value, this function will cause an `EnvVarError` to be thrown | ||
when you attempt to read the value using `asString` or a similar function. | ||
The `required()` check can be bypassed by passing `false`, i.e | ||
`required(false)` | ||
Example: | ||
```js | ||
const env = require('env-var') | ||
// Get the value of NODE_ENV as a string. Could be undefined since we're | ||
// not calling required() before asString() | ||
const NODE_ENV = env.get('NODE_ENV').asString() | ||
// Read PORT variable and ensure it's in a valid port range. If it's not in | ||
// valid port ranges, not set, or empty an EnvVarError will be thrown | ||
const PORT = env.get('PORT').required().asPortNumber() | ||
// If mode is production then this is required | ||
const SECRET = env.get('SECRET').required(NODE_ENV === 'production').asString() | ||
``` | ||
#### convertFromBase64() | ||
It's a common need to set an environment variable in base64 format. This | ||
function can be used to decode a base64 environment variable to UTF8. | ||
For example if we run the script script below, using the command `DB_PASSWORD= | ||
$(echo -n 'secret_password' | base64) node`, we'd get the following results: | ||
```js | ||
console.log(process.env.DB_PASSWORD) // prints "c2VjcmV0X3Bhc3N3b3Jk" | ||
// dbpass will contain the converted value of "secret_password" | ||
const dbpass = env.get('DB_PASSWORD').convertFromBase64().asString() | ||
``` | ||
#### asPortNumber() | ||
Converts the value of the environment variable to an integer and verifies it's | ||
within the valid port range of 0-65535. As a result well known ports are | ||
considered valid by this function. | ||
#### asEnum(validValues: string[]) | ||
Converts the value to a string, and matches against the list of valid values. | ||
If the value is not valid, an error will be raised describing valid input. | ||
#### asInt() | ||
Attempt to parse the variable to an integer. Throws an exception if parsing | ||
fails. This is a strict check, meaning that if the *process.env* value is "1.2", | ||
an exception will be raised rather than rounding up/down. | ||
#### asIntPositive() | ||
Performs the same task as _asInt()_, but also verifies that the number is | ||
positive (greater than or equal to zero). | ||
#### asIntNegative() | ||
Performs the same task as _asInt()_, but also verifies that the number is | ||
negative (less than or equal to zero). | ||
#### asFloat() | ||
Attempt to parse the variable to a float. Throws an exception if parsing fails. | ||
#### asFloatPositive() | ||
Performs the same task as _asFloat()_, but also verifies that the number is | ||
positive (greater than or equal to zero). | ||
#### asFloatNegative() | ||
Performs the same task as _asFloat()_, but also verifies that the number is | ||
negative (less than or equal to zero). | ||
#### asString() | ||
Return the variable value as a String. Throws an exception if value is not a | ||
String. It's highly unlikely that a variable will not be a String since all | ||
*process.env* entries you set in bash are Strings by default. | ||
#### asBool() | ||
Attempt to parse the variable to a Boolean. Throws an exception if parsing | ||
fails. The var must be set to either "true", "false" (upper or lowercase), | ||
0 or 1 to succeed. | ||
#### asBoolStrict() | ||
Attempt to parse the variable to a Boolean. Throws an exception if parsing | ||
fails. The var must be set to either "true" or "false" (upper or lowercase) to | ||
succeed. | ||
#### asJson() | ||
Attempt to parse the variable to a JSON Object or Array. Throws an exception if | ||
parsing fails. | ||
#### asJsonArray() | ||
The same as _asJson_ but checks that the data is a JSON Array, e.g. [1,2]. | ||
#### asJsonObject() | ||
The same as _asJson_ but checks that the data is a JSON Object, e.g. {a: 1}. | ||
#### asArray([delimiter: string]) | ||
Reads an environment variable as a string, then splits it on each occurence of | ||
the specified _delimiter_. By default a comma is used as the delimiter. For | ||
example a var set to "1,2,3" would become ['1', '2', '3']. Example outputs for | ||
specific values are: | ||
* Reading `MY_ARRAY=''` results in `[]` | ||
* Reading `MY_ARRAY='1'` results in `['1']` | ||
* Reading `MY_ARRAY='1,2,3'` results in `['1', '2', '3']` | ||
#### asUrlString() | ||
Verifies that the variable is a valid URL string and returns the validated | ||
string. The validation is performed by passing the URL string to the | ||
[Node.js URL constructor](https://nodejs.org/docs/latest/api/url.html#url_class_url). | ||
Note that URLs without paths will have a default path `/` appended when read, e.g. | ||
`https://api.acme.org` would become `https://api.acme.org/`. Always use URL | ||
safe utilities included in the | ||
[Node.js URL module](https://nodejs.org/docs/latest/api/url.html) to create | ||
valid URL strings, instead of error prone string concatenation. | ||
#### asUrlObject() | ||
Verifies that the variable is a valid URL string using the same method as | ||
`asUrlString()`, but instead returns the resulting URL instance. For details | ||
see the [Node.js URL docs](https://nodejs.org/docs/latest/api/url.html#url_class_url). | ||
#### asRegExp([flags: string]) | ||
Read in the variable and construct a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | ||
instance using its value. An optional `flags` argument is supported. The string | ||
passed for `flags` is passed as the second argument to the `RegExp` constructor. | ||
### EnvVarError() | ||
This is the error class used to represent errors raised by this module. Sample | ||
usage: | ||
```js | ||
const env = require('env-var') | ||
let value = null | ||
try { | ||
// will throw if you have not set this variable | ||
value = env.get('MISSING_VARIABLE').required().asString() | ||
// if catch error is set, we'll end up throwing here instead | ||
throw new Error('some other error') | ||
} catch (e) { | ||
if (e instanceof env.EnvVarError) { | ||
console.log('we got an env-var error', e) | ||
} else { | ||
console.log('we got some error that wasn\'t an env-var error', e) | ||
} | ||
} | ||
``` | ||
## Examples | ||
```js | ||
const env = require('env-var'); | ||
// Normally these would be set using "export VARNAME" or similar in bash | ||
process.env.STRING = 'test'; | ||
process.env.INTEGER = '12'; | ||
process.env.BOOL = 'false'; | ||
process.env.JSON = '{"key":"value"}'; | ||
process.env.COMMA_ARRAY = '1,2,3'; | ||
process.env.DASH_ARRAY = '1-2-3'; | ||
// The entire process.env object | ||
const allVars = env.get(); | ||
// Returns a string. Throws an exception if not set or empty | ||
const stringVar = env.get('STRING').required().asString(); | ||
// Returns an int, undefined if not set, or throws if set to a non integer value | ||
const intVar = env.get('INTEGER').asInt(); | ||
// Return a float, or 23.2 if not set | ||
const floatVar = env.get('FLOAT').default('23.2').asFloat(); | ||
// Return a Boolean. Throws an exception if not set or parsing fails | ||
const boolVar = env.get('BOOL').required().asBool(); | ||
// Returns a JSON Object, undefined if not set, or throws if set to invalid JSON | ||
const jsonVar = env.get('JSON').asJson(); | ||
// Returns an array if defined, or undefined if not set | ||
const commaArray = env.get('COMMA_ARRAY').asArray(); | ||
// Returns an array if defined, or undefined if not set | ||
const commaArray = env.get('DASH_ARRAY').asArray('-'); | ||
// Returns the enum value if it's one of dev, test, or live | ||
const enumVal = env.get('ENVIRONMENT').asEnum(['dev', 'test', 'live']) | ||
``` | ||
### accessors | ||
A property that exposes the built-in accessors that this module uses to parse | ||
and validate values. These work similarly to the *asString()* and other | ||
accessors exposed on the *variable* type documented above, however they accept | ||
a *String* as their first argument, e.g: | ||
```js | ||
const env = require('env-var') | ||
// Validate that the string is JSON, and return the parsed result | ||
const myJsonDirectAccessor = env.accessors.asJson(process.env.SOME_JSON) | ||
const myJsonViaEnvVar = env.get('SOME_JSON').asJson() | ||
``` | ||
All of the documented *asX()* accessors above are available. These are useful | ||
if you need to build a custom accessor using the *extraAccessors* functionality | ||
described below. | ||
## extraAccessors | ||
When calling `from()` you can also pass an optional parameter containing | ||
additional accessors that will be attached to any variables gotten by that | ||
`env-var` instance. | ||
Accessor functions must accept at least one argument: | ||
- `{*} value`: The value that the accessor should process. | ||
**Important:** Do not assume that `value` is a string! | ||
Example: | ||
```js | ||
const { from } = require('env-var') | ||
// Environment variable that we will use for this example: | ||
process.env.ADMIN = 'admin@example.com' | ||
// Add an accessor named 'asEmail' that verifies that the value is a | ||
// valid-looking email address. | ||
const env = from(process.env, { | ||
asEmail: (value) => { | ||
const split = String(value).split('@') | ||
// Validating email addresses is hard. | ||
if (split.length !== 2) { | ||
throw new Error('must contain exactly one "@"') | ||
} | ||
return value | ||
} | ||
}) | ||
// We specified 'asEmail' as the name for the accessor above, so now | ||
// we can call `asEmail()` like any other accessor. | ||
let validEmail = env.get('ADMIN').asEmail() | ||
``` | ||
The accessor function may accept additional arguments if desired; these must be | ||
provided explicitly when the accessor is invoked. | ||
For example, we can modify the `asEmail()` accessor from above so that it | ||
optionally verifies the domain of the email address: | ||
```js | ||
const { from } = require('env-var') | ||
// Environment variable that we will use for this example: | ||
process.env.ADMIN = 'admin@example.com' | ||
// Add an accessor named 'asEmail' that verifies that the value is a | ||
// valid-looking email address. | ||
// | ||
// Note that the accessor function also accepts an optional second | ||
// parameter `requiredDomain` which can be provided when the accessor is | ||
// invoked (see below). | ||
const env = from(process.env, { | ||
asEmail: (value, requiredDomain) => { | ||
const split = String(value).split('@') | ||
// Validating email addresses is hard. | ||
if (split.length !== 2) { | ||
throw new Error('must contain exactly one "@"') | ||
} | ||
if (requiredDomain && (split[1] !== requiredDomain)) { | ||
throw new Error(`must end with @${requiredDomain}`) | ||
} | ||
return value | ||
} | ||
}) | ||
// We specified 'asEmail' as the name for the accessor above, so now | ||
// we can call `asEmail()` like any other accessor. | ||
// | ||
// `env-var` will provide the first argument for the accessor function | ||
// (`value`), but we declared a second argument `requiredDomain`, which | ||
// we can provide when we invoke the accessor. | ||
// Calling the accessor without additional parameters accepts an email | ||
// address with any domain. | ||
let validEmail = env.get('ADMIN').asEmail() | ||
// If we specify a parameter, then the email address must end with the | ||
// domain we specified. | ||
let invalidEmail = env.get('ADMIN').asEmail('github.com') | ||
``` | ||
This feature is also available for TypeScript users. The `ExtensionFn` type is | ||
exposed to help in the creation of these new accessors. | ||
```ts | ||
import { from, ExtensionFn, EnvVarError } from 'env-var' | ||
// Environment variable that we will use for this example: | ||
process.env.ADMIN = 'admin@example.com' | ||
const asEmail: ExtensionFn<string> = (value) => { | ||
const split = String(value).split('@') | ||
// Validating email addresses is hard. | ||
if (split.length !== 2) { | ||
throw new Error('must contain exactly one "@"') | ||
} | ||
return value | ||
} | ||
const env = from(process.env, { | ||
asEmail | ||
}) | ||
// Returns the email string if it's valid, otherwise it will throw | ||
env.get('ADMIN').asEmail() | ||
``` | ||
You can view an example of composing built-in accessors made available by | ||
`env.accessors` in an extra accessor at *examples/custom-accessor.js*. | ||
## Contributing | ||
Contributions are welcomed and discussed in the `CONTRIBUTING.md` file in this | ||
repo. If you'd like to discuss an idea open an issue, or a PR with an initial | ||
implementation. | ||
## Contributors | ||
* @aautio | ||
@@ -635,0 +143,0 @@ * @caccialdo |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
673
39282
152