Skip to content

Commit

Permalink
feat: add preload
Browse files Browse the repository at this point in the history
  • Loading branch information
danielfsousa committed Sep 16, 2019
1 parent de37411 commit 5ba742e
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 19 deletions.
11 changes: 10 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,14 @@ module.exports = {
'no-useless-constructor': 0,
'@typescript-eslint/no-useless-constructor': 1,
'no-dupe-class-members': 0
}
},
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/no-var-requires': 0,
'@typescript-eslint/explicit-function-return-type': 0
}
}
]
}
32 changes: 26 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ async function main () {
main()
```

#### Using dotenv-azure
#### Using dotenv-azure programmatically

You should call `dotenv-azure` rigth after the initialization of your app. Since the method `.config()` returns a promise, you have to call it inside an async function:
You should call `dotenv-azure` before the initialization of your app. Since the method `.config()` returns a promise, you have to call it inside an async function:
```javascript
const DotenvAzure = require('dotenv-azure')
const dotenvAzure = new DotenvAzure()

async function main () {
const dotenvAzure = new DotenvAzure()
const { parsed } = await dotenvAzure.config()

// `parsed` is an object containing:
Expand All @@ -100,18 +100,38 @@ async function main () {

// process.env now has the keys and values from the parsed result
console.log(process.env)

// start app
// ...
}

main()
```

## Preload
#### Preload dotenv-azure

You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#cli_r_require_module) to preload `dotenv-azure`. By doing this, you do not need to require and load `dotenv-azure` in your application code.

```bash
node -r dotenv-azure/config your_script.js
```

TODO
To enable [safe mode](https://danielfsousa.github.io/dotenv-azure/interfaces/dotenvazureconfigoptions.html#safe) you should require `config-safe`:

```bash
node -r dotenv-azure/config-safe your_script.js
```

## Rules

TODO
`dotenv-azure` uses `dotenv` under the covers, so the same [rules](https://github.com/motdotla/dotenv/blob/master/README.md#rules) for `.env` files apply here as well.

When populating `process.env` `dotenv-azure` will follow these steps:

1. Values within the process's environment (i.e. an environment variable exists) takes precedence over everything else.
2. For values defined in the `.env` file, and not present in the environemnt, `process.env` will be populated with those values.
3. `dotenv-azure` will search for the required environment variables to access azure's services after loading variables from the `.env` file.
4. For values defined within the process's environment, in the `.env` file or in the Azure App Configuration, where the value is prefixed with `kv:` what follows is assumed to be the secret identifier of a secret stored in Key Vault, and so `dotenv-azure` will attempt to populate the value from Key Vault.

## Options

Expand Down
5 changes: 5 additions & 0 deletions config-rpc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const { DotenvAzure } = require('./dist/lib/dotenv-azure')

module.exports = function config() {
return options => new DotenvAzure().config(options)
}
10 changes: 10 additions & 0 deletions config-safe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const forceSync = require('sync-rpc')
const { populateProcessEnv } = require('./dist/lib/utils')
const configSync = forceSync(require.resolve('./config-rpc'))

const { parsed } = configSync({
safe: true,
allowEmptyValues: true
})

populateProcessEnv(parsed)
6 changes: 6 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const forceSync = require('sync-rpc')
const { populateProcessEnv } = require('./dist/lib/utils')
const configSync = forceSync(require.resolve('./config-rpc'))

const { parsed } = configSync()
populateProcessEnv(parsed)
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"@azure/core-http": "1.0.0-preview.3",
"@azure/identity": "^1.0.0-preview.3",
"@azure/keyvault-secrets": "^4.0.0-preview.5",
"dotenv": "^8.1.0"
"dotenv": "^8.1.0",
"sync-rpc": "^1.3.6"
}
}
13 changes: 2 additions & 11 deletions src/dotenv-azure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as fs from 'fs'
import dotenv, { DotenvParseOptions, DotenvParseOutput } from 'dotenv'
import { ManagedIdentityCredential, ClientSecretCredential } from '@azure/identity'
import { SecretsClient } from '@azure/keyvault-secrets'
import { testIfValueIsVaultSecret, compact, difference } from './utils'
import { testIfValueIsVaultSecret, compact, difference, populateProcessEnv } from './utils'
import { MissingEnvVarsError, InvalidKeyVaultUrlError } from './errors'
import {
DotenvAzureOptions,
Expand Down Expand Up @@ -47,7 +47,7 @@ export default class DotenvAzure {
const azureVars = await this.loadFromAzure(parsed)
const joinedVars = { ...azureVars, ...parsed }

this.populateProcessEnv(azureVars)
populateProcessEnv(azureVars)
if (safe) {
this.validateFromEnvExample(options, error)
}
Expand Down Expand Up @@ -87,15 +87,6 @@ export default class DotenvAzure {
return { ...appConfigVars, ...keyVaultSecrets }
}

/**
* Add variable if does not exist in process.env
* @param variables - an object with keys and values
*/
protected populateProcessEnv(variables: VariablesObject): void {
//
Object.entries(variables).forEach(([key, val]) => key in process.env || (process.env[key] = val))
}

protected validateFromEnvExample(options: DotenvAzureConfigOptions, dotenvError?: Error): void {
const { allowEmptyValues = false, example = '.env.example', path = '.env' } = options
const processEnv = allowEmptyValues ? process.env : compact(process.env)
Expand Down
8 changes: 8 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,11 @@ export function testIfValueIsVaultSecret(value: string): URL | undefined {
}
return keyVaultUrl
}

/**
* Add variable if does not exist in process.env
* @param variables - an object with keys and values
*/
export function populateProcessEnv(variables: VariablesObject): void {
Object.entries(variables).forEach(([key, val]) => key in process.env || (process.env[key] = val))
}
12 changes: 12 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3217,6 +3217,11 @@ get-own-enumerable-property-symbols@^3.0.0:
resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz#b877b49a5c16aefac3655f2ed2ea5b684df8d203"
integrity sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg==

get-port@^3.1.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/get-port/-/get-port-3.2.0.tgz#dd7ce7de187c06c8bf353796ac71e099f0980ebc"
integrity sha1-3Xzn3hh8Bsi/NTeWrHHgmfCYDrw=

get-stdin@7.0.0, get-stdin@^7.0.0:
version "7.0.0"
resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-7.0.0.tgz#8d5de98f15171a125c5e516643c7a6d0ea8a96f6"
Expand Down Expand Up @@ -7710,6 +7715,13 @@ symbol-tree@^3.2.2:
resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2"
integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==

sync-rpc@^1.3.6:
version "1.3.6"
resolved "https://registry.yarnpkg.com/sync-rpc/-/sync-rpc-1.3.6.tgz#b2e8b2550a12ccbc71df8644810529deb68665a7"
integrity sha512-J8jTXuZzRlvU7HemDgHi3pGnh/rkoqR/OZSjhTyyZrEkkYQbk7Z33AXp37mkPfPpfdOuj7Ex3H/TJM1z48uPQw==
dependencies:
get-port "^3.1.0"

table@^5.2.3:
version "5.4.6"
resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e"
Expand Down

0 comments on commit 5ba742e

Please sign in to comment.