Data Config Promise
This utility provides a Data class which allows for the manipulation of a data object using a dot deliminated path.
Installation
$ npm install data-config-promise
Usage
import Data from "data-config-promise";
const myData = new Data({
value1: "hello",
value2: {
value3: "world"
}
});
// > "hello"
console.info(myData.get("value1"));
// > "world"
console.info(myData.get("value2.value3"));
// > null
console.info(myData.get("value3"));
// > "hello world"
console.info(myData.get("value3", "hello world"));
The Data class provides get, set, del and has methods to get, set, delete and check for properties.
import Data from "data-config-promise";
// Create the Data object, and use '.' for the deliminator.
const myData = new Data({}, ".");
// > false
myData.has("value1");
// > null
myData.get("value1");
myData.set("value1", "hello world");
// > true
myData.has("value1");
// > "hello world"
myData.get("value1");
myData.del("value1");
// > false
myData.has("value1");
// > null
myData.get("value1");
// > false
myData.has("value2.something");
myData.set("value2.something", "foo");
// > { "something": "foo" }
myData.get("value2");
Setting the data using the Data object also updates the provided data object, for example:
import Data from "data-config-promise";
const data = {};
const myData = new Data(data);
myData.set("value1.value2", "hello world");
// > { "value1": { "value2": "hello world" } }
console.dir(data);
Finally, you can also create references from a larger data object, which will kepp each other updated:
import Data from "data-config-promise";
const data = {
"settings": {
"module1": {
"value1": "hello world"
},
"module2": {
"value1": "foo bar"
}
}
};
const myData = new Data(data);
let ref1 = myData.ref("settings.module1");
let ref2 = myData.ref("settings.module2");
// > "hello world"
console.info(myData.get("settings.module1.value1"));
console.info(ref1.get("value1"));
// > "foo bar"
console.info(myData.get("settings.module2.value1"));
console.info(ref2.get("value1"));
ref1.set("value1", "foo bar");
// > "foo bar"
console.info(myData.get("settings.module1.value1"));
console.info(ref1.get("value1"));
// > "foo bar"
console.info(myData.get("settings.module2.value1"));
console.info(ref2.get("value1"));
// > {"settings": {"module1": {"value1": "foo bar"}}, "module2": {"value1": "foo bar"}}}
console.dir(data);
Loading and saving
The Data class also provides a means to load ans save the data to a JSON file. Comments are supported in the JSON file.
import Data from "data-config-promise";
let config = new Data();
config.loadFromFile("path/to/config-file.json").then(() => {
config.set("value1", "hello");
return config.saveToFile();
});
Testing
A Jest test suite has been provided and can be run by:
$ npm test
or
$ gulp test