hex-object
TypeScript icon, indicating that this package has built-in type declarations

1.3.2 • Public • Published

hex-object

This is a small collection of utilities for dealing with object manipulation, aimed primarily at the use case of configuration objects.

"Dotted-path" shortcut keys

This module implements utilities to support a short alternate syntax for deep structures:

{
	'login.strategies.twilio.api': {
		'id': 'foo',
		'key': 'bar'
	},
	'login.strategies.local.store': 'redis'
}
// - or -
{
	'login.strategies': {
		'twilio.api': {
			'id': 'foo',
			'key': 'bar'
		},
		'local.store': 'redis'
	}
}

can be used in place of the "normalized" JSON equivalent:

{
"login": { "strategies": {
		"twilio": { "api": {
			"id": "foo",
			"key": "bar"
		} },
		"local": { "store": "redis" }
	} }
}

This module's normalize converts either of the former into the latter. After an object is normalized, you can use get, set, push, and concat to operate it on it using shortcuts:

const obj = require('hex-object'), conf = require('./login-conf');
obj.normalize(conf);
obj.get(conf, 'login.strategies.local');
// { 'store': 'redis' }

Environment-specific overrides

The root paths dev, test and prod are considered special namespaces that refer specifically to that environment (as determined by process.env.NODE_ENV).

test.js:

console.log(require('hex-object').wrap({
	't': 'base',
	'dev': { 't': 'dev' },
	'test': { 't': 'test' },
	'prod': { 't': 'prod' }
}).get('t'));
$ NODE_ENV=testing node test
test
$ NODE_ENV=PROD node test
prod
$ node test
dev

The interpretation of the environment variable is relatively loose, and development is assumed as the default.

Wrapping

If you want to do more than one operation on an object, it can be helpful to wrap it:

const obj = require('hex-object'), conf = obj.wrap(require('./login-conf'));
conf
    .normalize()
    .set('login.strategies.local.store', 'postgres');

conf.get('login.strategies.local');
// { 'store': 'postgres' });

Refer to the tests for more usage examples.

Overriding & Augmenting

Sometimes it is necessary to combine configuration from various sources in the same key space.

This is how it works:

const obj = require('hex-object'),
     conf = require('./conf'),
// { 'port': 8000, 'data-source': 'fs', 'plugins': [ 'a', 'b' ] }
  modConf = require('./mod/conf');
// { 'plugins': [ 'c' ], 'data-source': 'redis' }

obj.augment(conf, modConf);
// {
//     'port': 8000,
//     'data-source': 'redis', // later-declared value "wins"
//     'plugins': [ 'a', 'b', 'c' ] // except in cases of arrays, which get merged
// }

Readme

Keywords

none

Package Sidebar

Install

npm i hex-object

Weekly Downloads

2

Version

1.3.2

License

MIT

Unpacked Size

17.1 kB

Total Files

7

Last publish

Collaborators

  • snyder13