@chris-lewis/fitbit-utils
Version:
Common utility modules for common tasks across projects.
64 lines (56 loc) • 1.27 kB
JavaScript
import { readFileSync, writeFileSync } from 'fs';
var data = {};
var dbPath = '';
/**
* Save the data to the filesystem.
*/
var save = function save() {
return writeFileSync(dbPath, data, 'json');
};
/**
* Initialise the data in the filesystem to empty object.
*
* @param {string} appName - App name, used to save data for this app.
*/
export var init = function init(appName) {
if (!appName) {
throw new Error('Please specify the app name!');
}
dbPath = "".concat(appName, ".json");
try {
data = readFileSync(dbPath, 'json');
console.log("Loaded ".concat(dbPath));
} catch (e) {
console.log(e);
data = {};
save();
}
};
/**
* Determine if a key contains data.
*
* @param {string} key - Key to search.
* @returns {boolean} true if the key has defined value.
*/
export var contains = function contains(key) {
return get(key) !== null;
};
/**
* Get a value for a given key.
*
* @param {string} key - Key to search.
* @returns {*} Value associated, if any.
*/
export var get = function get(key) {
return data[key];
};
/**
* Set a value and save it.
*
* @param {string} key - Key to use.
* @param {*} value - Value to use.
*/
export var set = function set(key, value) {
data[key] = value;
save();
};