Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
iansu committed Apr 22, 2019
0 parents commit 2bd5221
Show file tree
Hide file tree
Showing 29 changed files with 5,437 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# http://editorconfig.org
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 100
trim_trailing_whitespace = true

[*.md]
max_line_length = 0
trim_trailing_whitespace = false

[COMMIT_EDITMSG]
max_line_length = 0
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build
coverage
3 changes: 3 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "eslint-config-neo/config-backend"
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
build
coverage
node_modules
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
8
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"printWidth": 100,
"singleQuote": true
}
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0 (April 11, 2019)

Initial release! :tada:
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Neo Financial Technologies Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
119 changes: 119 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Config Dug

![Config Dug](https://github.com/neofinancial/config-dug/blob/master/config-dug.png "Config Dug")

Config loader with support for AWS Secrets Manager.

![TypeScript 3.4.3](https://img.shields.io/badge/TypeScript-3.4.3-brightgreen.svg)

## Usage

### Installation

| yarn | npm |
|---------------------|------------------------|
|`yarn add config-dug`|`npm install config-dug`|

### Create your config files

`config-dug` looks in several places for your config, including config files in your project, environment variables and [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/). `config-dug` allows you to write your config files in either TypeScript or JavaScript. You are expected to export a default object from your config file:

```ts
// config.default.ts
export default {
API_ENDPOINT: 'https://api.kanye.rest/'
};
```

```js
// config.default.js
module.exports = {
API_ENDPOINT: 'https://api.kanye.rest/'
};
```

Settings from these different sources are merged together into a single config object in the following order:

1. `config.default.{ts|js}`
1. `config.${NODE_ENV}.{ts|js}`
1. `config.local.{ts|js}`
1. AWS Secrets Manager
1. Environment variables

By default your config files need to be placed in the root directory of your project. If you want to keep config files in a different directory see [Customizing Config Loading](#customizing-config-loading).

### Import config

Import `config-dug` anywhere in your code where you want to access your config. All of your settings are available on the imported object:

```ts
// app.ts
import config from 'config-dug';

console.log(config.API_ENDPOINT);
// https://api.kanye.rest/
```

```js
// app.js
const config = require('config-dug');

console.log(config.API_ENDPOINT);
// https://api.kanye.rest/
```

### Using AWS Secrets Manager

In order to use AWS Secrets Manager you have to add a `AWS_SECRETS_MANAGER_NAME` or `awsSecretsManagerName` setting to your config that specifies the name of the secret to look up:

```ts
// config.default.ts
export default {
AWS_SECRETS_MANAGER_NAME: 'production/myapp/config',
API_ENDPOINT: 'https://api.kanye.rest/'
}
```

In addition to specifying the secret name you can also provide a region using the `AWS_SECRETS_MANAGER_REGION` or `awsSecretsManagerRegion` setting:

```ts
// config.default.ts
export default {
AWS_SECRETS_MANAGER_NAME: 'production/myapp/config',
AWS_SECRETS_MANAGER_REGION: 'us-west-2',
API_ENDPOINT: 'https://api.somecompany.com'
}
```

This package uses the [aws-sdk](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/) internally. Refer to their documentation for information about [authentication](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html), configuring a default [region](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-region.html) and configuring [access control for AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html).

## Advanced

### Customizing Config Loading

If you want to load config files from a directory other than the project root you can import the `loadConfig` function and use it directly.

```ts
import { loadConfig } from 'config-dug';

loadConfig('config');
```

This will import your config files from the `config` directory. The path you specify must be relative to your project root.

### Debugging

`config-dug` uses the [debug](https://github.com/visionmedia/debug) library. To print debug messages for `config-dug` set `DEBUG=config-dug`.

## Contributing

### Running Tests

1. Fork this repo
1. Clone the forked repo
1. Install dependencies: `yarn`
1. Run tests: `yarn test`

## Credits

This project was inspired by [config3](https://github.com/focusaurus/config3) and [config4](https://github.com/autolotto/config4).
Binary file added config-dug.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node'
};
60 changes: 60 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"name": "config-dug",
"version": "1.0.0",
"description": "Config loader with support for AWS Secrets Manager",
"author": "Neo Financial Engineering <[email protected]>",
"main": "build/index.js",
"types": "build/index.d.ts",
"license": "MIT",
"homepage": "https://github.com/neofinancial/config-dug",
"repository": {
"type": "git",
"url": "https://github.com/neofinancial/config-dug.git"
},
"engines": {
"node": ">=8.0.0"
},
"scripts": {
"build": "tsc -p tsconfig.build.json",
"watch": "tsc --watch -p tsconfig.build.json",
"clean": "rimraf build",
"test": "jest",
"lint": "eslint \"**/*.{ts,js}\"",
"format": "prettier --write \"**/*.{ts,js,json,graphql,md}\"",
"format:check": "prettier --debug-check \"**/*.{ts,js,json,graphql,md}\"",
"prepare": "rimraf build && tsc -p tsconfig.build.json"
},
"files": [
"/build/**/*.js",
"/build/**/*.d.ts"
],
"keywords": [
"config",
"configuration",
"typescript",
"javascript",
"node"
],
"dependencies": {
"aws-param-store": "^2.1.0",
"aws-sdk": "^2.437.0",
"debug": "^4.1.1",
"lodash": "^4.17.11"
},
"devDependencies": {
"@types/aws-param-store": "^2.1.0",
"@types/debug": "^4.1.3",
"@types/jest": "^24.0.11",
"@types/lodash": "^4.14.123",
"@types/node": "^11.13.2",
"eslint": "^5.16.0",
"eslint-config-neo": "^0.1.0",
"husky": "^1.3.1",
"jest": "^24.7.1",
"lint-staged": "^8.1.5",
"prettier": "^1.16.4",
"rimraf": "^2.6.3",
"ts-jest": "^24.0.2",
"typescript": "^3.4.3"
}
}
7 changes: 7 additions & 0 deletions src/__mocks__/get-secret.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import awsSecretsManagerResponse from '../../test/fixtures/secrets/aws-secrets-manager-response.json';

function getSecret(_: string, __: string): object {
return JSON.parse(awsSecretsManagerResponse.Value);
}

export default getSecret;
20 changes: 20 additions & 0 deletions src/get-secret.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable no-console */

import awsParamStore from 'aws-param-store';

function getSecret(secretName: string, region: string): object {
try {
const secret = awsParamStore.getParameterSync(`/aws/reference/secretsmanager/${secretName}`, {
region
});

return JSON.parse(secret.Value);
} catch (error) {
console.error('ERROR: Unable to get secret from AWS Secrets Manager');
console.error(error);

return {};
}
}

export default getSecret;
115 changes: 115 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/* eslint-disable no-console */

import fs from 'fs';
import path from 'path';
import createDebug from 'debug';
import mapValues from 'lodash/mapValues';

import getSecret from './get-secret';

const debug = createDebug('config-dug');

interface ConfigObject {
[key: string]: string | boolean | number;
}

function resolveFile(appDirectory: string, configPath: string, fileName: string): string {
if (fs.existsSync(path.resolve(appDirectory, configPath, `${fileName}.ts`))) {
debug(
'resolved config file',
fileName,
path.resolve(appDirectory, configPath, `${fileName}.ts`)
);

return path.resolve(appDirectory, configPath, `${fileName}.ts`);
} else if (fs.existsSync(path.resolve(appDirectory, configPath, `${fileName}.js`))) {
debug(
'resolved config file',
fileName,
path.resolve(appDirectory, configPath, `${fileName}.js`)
);

return path.resolve(appDirectory, configPath, `${fileName}.js`);
} else {
debug('unable to resolve config file', fileName);

return undefined;
}
}

function loadFile(filePath: string): object {
if (filePath) {
debug('loading config file', filePath);

try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const config = require(filePath);

return config.default ? config.default : config;
} catch (error) {
console.error(`ERROR: Unable to load config file: ${filePath}`);
console.error(error);
}
}
}

function loadSecrets(config: {
AWS_SECRETS_MANAGER_NAME?: string;
AWS_SECRETS_MANAGER_REGION?: string;
awsSecretsManagerName?: string;
awsSecretsManagerRegion?: string;
}): object {
const secretName = config.AWS_SECRETS_MANAGER_NAME || config.awsSecretsManagerName;
const region = config.AWS_SECRETS_MANAGER_REGION || config.awsSecretsManagerRegion || 'us-east-1';

if (secretName) {
debug('loading config from AWS Secrets Manager', secretName, region);

return getSecret(secretName, region);
} else {
return {};
}
}

function loadEnvironment(): object {
debug('loading config from environment variables');

return mapValues(
process.env,
(value: string): string | number | boolean => {
if (value.toLowerCase() === 'true') return true;
if (value.toLowerCase() === 'false') return false;
if (value.match(/^\d+.\d$/)) return parseFloat(value);
if (value.match(/^\d$/)) return parseInt(value, 10);

return value;
}
);
}

function loadConfig(configPath = ''): ConfigObject {
const appDirectory = fs.realpathSync(process.cwd());
const environment = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';

debug('loading config from', path.resolve(appDirectory, configPath));

const defaultConfig = loadFile(resolveFile(appDirectory, configPath, 'config.default'));
const environmentConfig = loadFile(
resolveFile(appDirectory, configPath, `config.${environment}`)
);
const localConfig = loadFile(resolveFile(appDirectory, configPath, 'config.local'));
const fileConfig = Object.assign({}, defaultConfig, environmentConfig, localConfig);
const config = Object.assign({}, fileConfig, loadSecrets(fileConfig), loadEnvironment());

return config;
}

function init(): ConfigObject {
debug('loading default config');
const config = loadConfig();

return config;
}

export default init();
export { loadConfig };
Loading

0 comments on commit 2bd5221

Please sign in to comment.