1.0.1 • Published 9 years ago

light-config v1.0.1

Weekly downloads
1
License
ISC
Repository
github
Last release
9 years ago

Light Config Build status

Share specific subsets of your server-side config with the browser

Installation

npm i light-config --save

The Problem

Say one has the following JSON config for a Node.js app:

{
	"version": "1.0.0",
	"environment": "production1",
	"services": {
		"payments": {
			"url": "https://api/payments"
		},

		"users": {
			"url": "https://api/users"
		}
	},

	"clusters": {
		[...]
	},

	"messageQueue": {
		[...]
	}
}

If one wishes to retrieve the services property in the browser to make a client-side XMLHttpRequest, it becomes necessary to pass the configuration to the client. In the above example, the other properties are only relevant to the server, and passing a large config in its entirety will result in an increased response size.

The Solution

Light Config allows one to create a subset of a config. For example:

// ECMAScript 5: var lightConfig = require('light-config');
import lightConfig from 'light-config';
import serverConfig from './serverConfig.json';

const clientConfig = lightConfig(serverConfig, ['environment', 'services.users']);

/* Outputs:
 * {
 *		environment: 'production1',
 		services: {
 			users: {
 				url: 'https://api/users'
 			}
 		}
 * }

console.log(clientConfig);

As can be seen, the format of the server config is maintained (i.e. clientConfig.services.users.url). This is particularly useful when developing isomorphic apps.

clientConfig can be passed to the client in various ways. In Express, one could pass it as a cookie header:

response.set('Set-Cookie', JSON.stringify(clientConfig));

Alternatively, one could pass it to a template and attach it to the window:

response.render('view.handlebars', { clientConfig: JSON.stringify(clientConfig) });

// view.handlebars
<script>window.NAMESPACE.config = {{{ clientConfig }}}</script>

API

lightConfig(serverConfig, propertyTrees)

Returns a subset of the specified server config object according to the propertyTrees array, which can contain root properties (e.g. ['environment']) or deep properties (e.g. ['services.users']); the latter honours the existing contract.