Data
Installation
Install the package normally using NPM or Yarn.
# Npm
npm i @depax/data
# Yarn
yarn add @depax/data
Usage
import Data from "@depax/data";
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 "@depax/data";
// 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 "@depax/data";
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 "@depax/data";
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);
Config: Loading and saving
There is also a Config class which provides a means to load and save the data to a JSON or YAML file.
Note: Comments are supported in the JSON file, however they will not be restored when the config file is saved again.
import { Config } from "@depax/data";
const data = new Config("path/to/config-file.json");
// or, for YAML;
// const data = new Config("path/to/config-file.yaml");
await config.load();
config.set("value1", "hello");
await config.save();