Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
FGRibreau committed Dec 23, 2014
1 parent b108da4 commit fed24cc
Show file tree
Hide file tree
Showing 6 changed files with 246 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .checkbuild
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"checkbuild": {
"enable": ["jshint", "jscs", "jsinspect", "nsp"],
"enable": ["jshint", "jsinspect", "david", "nsp"],
// don't exit immediately if one of the tools reports an error
"continueOnError": true,
// don't exit(1) even if we had some failures
Expand Down
47 changes: 45 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,47 @@
common-env
common-env [![Build Status](https://drone.io/github.com/FGRibreau/common-env/status.png)](https://drone.io/github.com/FGRibreau/common-env/latest)
[![Deps](https://david-dm.org/FGRibreau/common-env.png)](https://david-dm.org/FGRibreau/common-env)
[![Version](http://badge.fury.io/js/common-env.png)](https://david-dm.org/FGRibreau/common-env)

==========

A little helper I use everywhere
A little helper I use everywhere for configuration. Environment variables are a really great way to quickly change a program behavior.

<p align="center">
<img style="width:100%" src="./docs/configuration.gif"/>
</p>

# npm

```shell
npm install common-env
```

# Usage

```javascript
var env = require('common-env');

// AMQP_CONNECT=true node test.js
var config = env.getOrElseAll({
amqp: {
login: 'guest',
password: 'guest',
host: 'localhost',
port: 5672,
connect: false
},

FULL_UPPER_CASE: {
PORT: 8080
},

MICROSTATS: {
HASHKEY: 'B:mx:global'
}
});

t.strictEqual(config.amqp.login, 'plop'); // converted from env
t.strictEqual(config.amqp.port, 5672);
t.strictEqual(config.amqp.connect, true); // converted from env
t.strictEqual(config.FULL_UPPER_CASE.PORT, 8080);
```
Binary file added docs/configuration.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
83 changes: 83 additions & 0 deletions lib/common-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*global process, module */
'use strict';
var PRINTED = Object.create(null);
var _ = require('lodash');

function env(logger) {

function log( /* args... */ ) {
if (!env.DISPLAY_LOG) {
return;
}
logger.info.apply(logger, arguments);
}

return {
getOrElse: function (key, def) {
if (process.env[key]) {
var val = _.isNumber(def) ? toInt(process.env[key]) : process.env[key];

if (seemsBoolean(val)) {
val = String(val).toLowerCase() === 'true';
}

if (!PRINTED[key]) {
PRINTED[key] = 1;
log('[env] ' + key + ' was defined, using ', String(val));
}
return val;
}

if (!PRINTED[key]) {
PRINTED[key] = 1;
log('[env] ' + key + ' was not defined, using default', String(def));
}
return def;
},

/**
* [getOrElseAll description]
* @param {Object} obj pair or {"ENV_VAR": {Number|String} defaultValue, ...}
* @return {Object} [description]
*/
getOrElseAll: function (vars, prefix) {
prefix = prefix || '';

return _.reduce(vars, function (out, val, k) {
var keyEnvName = k.toUpperCase();

if (_.isPlainObject(val)) {
out[k] = {};
_.extend(out[k], this.getOrElseAll(val, prefix + keyEnvName + '_'));
} else {
out[k] = this.getOrElse(prefix + keyEnvName, val);
}
return out;
}.bind(this), {});
},

getOrDie: function (key) {
// @todo refactor this shit.
var r = this.getOrElse(key, false);
if (r === false) {
throw new Error('(env) ' + key + ' MUST be defined');
}
return r;
}
};
}

/**
* @type {Boolean} true by default, display logs
*/
env.DISPLAY_LOG = true;

function toInt(str) {
return parseInt(str, 10);
}

function seemsBoolean(mixed) {
var v = String(mixed).toLowerCase();
return v === 'true' || v === 'false';
}
module.exports = env;
30 changes: 30 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "common-env",
"version": "1.0.0",
"description": "A little helper I use everywhere for configuration",
"main": "lib/common-env.js",
"directories": {
"doc": "docs",
"test": "test"
},
"scripts": {
"test": "mocha test"
},
"repository": {
"type": "git",
"url": "https://github.com/FGRibreau/common-env.git"
},
"author": "Francois-Guillaume Ribreau <[email protected]> (http://fgribreau.com/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/FGRibreau/common-env/issues"
},
"homepage": "https://github.com/FGRibreau/common-env",
"devDependencies": {
"chai": "^1.10.0",
"mocha": "^2.1.0"
},
"dependencies": {
"lodash": "^2.4.1"
}
}
87 changes: 87 additions & 0 deletions test/env.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
'use strict';

var envFactory = require('..');
var t = require('chai').assert;
var _ = require('lodash');

describe('env', function () {
var env, logger;

beforeEach(function () {
logger = {
calls: [],
info: function () {
this.calls.push(_.toArray(arguments).join(' '));
console.log.apply(console, arguments);
},
hasENV: function (env_var) {
return this.calls.some(function (line) {
return _.contains(line, env_var);
});
}
};
env = envFactory(logger);
process.env.AMQP_LOGIN = 'plop';
process.env.AMQP_CONNECT = 'tRue';
process.env.AMQP_CONNECT2 = 'false';
});

describe('.getOrElseAll', function () {

it('should return an object', function () {
var config = env.getOrElseAll({
AMQP: {
LoGiN: 'guest', // add a bug inside key name (mix lower/upper case)
PASSWORD: 'guest',
HOST: 'localhost',
PORT: 5672,
connect: false,
connect2: true,
PLOP: {
ok: {
heyheyhey: true
}
}
},

c: {
PORT: 8080,
root: ''
},

MICROSTATS: {
HASHKEY: 'B:mx:global'
}
});

t.strictEqual(config.AMQP.LoGiN, 'plop');
t.strictEqual(config.AMQP.PORT, 5672);
t.strictEqual(config.AMQP.PLOP.ok.heyheyhey, true);
t.strictEqual(config.AMQP.connect, true);
t.strictEqual(config.AMQP.connect2, false);
t.strictEqual(config.c.root, '');
});

it('should return ask for ENV vars', function () {
env.getOrElseAll({
plop: {
root_token: 'sdfopiqjsdfpoij',
api: {
endpoint_protocol: 'https',
endpoint_host: 'sqdfqsdf.cleverapps.io',
endpoint_port: ''
},
strategy: 'https://strategy.plop.net',
}
});

t.ok(logger.hasENV('PLOP_ROOT_TOKEN'), 'PLOP_ROOT_TOKEN');
t.ok(logger.hasENV('PLOP_API_ENDPOINT_PORT'), 'PLOP_API_ENDPOINT_PORT');
});
});

afterEach(function () {
delete process.env.AMQP_LOGIN;
});

});

0 comments on commit fed24cc

Please sign in to comment.