@martin-pettersson/config
v0.2.1
Published
A simple yet powerful configuration object
Downloads
2
Readme
Config
A simple yet powerful configuration object
Usage
You can instantiate an empty Config object or pass an object to the constructor to initialize it with an existing data structure.
// empty data structure
var config = new Config();
// existing data structure
var config = new Config({
name: "Martin Pettersson",
age: 27,
pets: [
"none",
"none",
"and",
"NONE!"
]
});
The configuration object uses dot-notation to navigate the data structure eg.
config.get("deeply.nested.value");
Given the following data structure the above statement would return true
{
deeply: {
nested: {
value: true
}
}
}
The same goes for adding values to the config object. Given an empty config object the following statement would create the same data structure.
config.put("deeply.nested.value", true);
The config object will create the nested data structure as needed or just append to the existing one.
Config Section
The ConfigSection extends Config but holds an internal reference to a Config object and operates on a given "section" of that config object. So the following statement:
var configSection = new ConfigSection("section", config);
configSection.put("name", "Martin");
Would produce the following data structure:
{
section: {
name: "Martin"
}
}
So the config section can only change the data structure within its given section name. What's more is that because the ConfigSection carries a reference to a Config object and operates on that reference. The Config object is being updated directly without the need for any additional bindings. Let's have a complete example of that:
var Config = require("@martin-pettersson/config").Config;
var ConfigSection = require("@martin-pettersson/config").ConfigSection;
var person = new Config();
var work = new ConfigSection("work", person);
person.put("firstName", "Martin");
person.put("lastName", "Pettersson");
person.put("age", 27);
// this will immediately be reflected on the person Config object
work.put("name", "Internetavdelningen");
console.log(
"%s %s is %d years old and works at %s",
person.get("firstName"),
person.get("lastName"),
person.get("age"),
// we can now access the nested config section value from the person object
person.get("work.name")
);
// output: Martin Pettersson is 27 years old and works at Internetavdelningen
The ConfigSection object can be a very powerful tool, each section of your program could be given their very own ConfigSection object and you could very easily keep a record of all the programs settings in one place. This makes persisting the settings a breeze. And as it actually extends Config it would of course pass:
if (configSection instanceof Config) { // ...