homedb
Version:
Better local storage.
111 lines (95 loc) • 2.82 kB
JavaScript
const fs = require("fs");
class HomeDB {
constructor({ path = "./home.db" } = {}) {
this.path = path;
if (!fs.existsSync(this.path)) this.#write({});
}
getAll() {
const data = this.#read();
return Object.entries(data).map(([id, value]) => ({ id, data: value }));
}
deleteAll() {
this.#write({});
return {};
}
set(id, value) {
this.#checkId(id);
if (value === undefined) throw new TypeError(`No data provided for ID "${id}"`);
const data = this.#read();
data[id] = value;
this.#write(data);
return value;
}
get(id) {
this.#checkId(id);
return this.#read()[id];
}
delete(id) {
this.#checkId(id);
const data = this.#read();
delete data[id];
this.#write(data);
}
push(id, value) {
this.#checkId(id);
if (value === undefined) throw new TypeError(`No data provided for ID "${id}"`);
const data = this.#read();
if (!Array.isArray(data[id])) data[id] = [];
data[id].push(value);
this.#write(data);
return data[id];
}
pull(id, predicate) {
this.#checkId(id);
if (typeof predicate !== "function") throw new TypeError(`Predicate for ID "${id}" must be a function`);
const arr = this.#read()[id];
if (!Array.isArray(arr)) throw new TypeError(`Data at ID "${id}" is not an array`);
return arr.filter(predicate);
}
pullDelete(id, condition) {
this.#checkId(id);
if (typeof condition !== "function") throw new TypeError(`Condition for ID "${id}" must be a function`);
const arr = this.#read()[id];
if (!Array.isArray(arr)) throw new TypeError(`Data at ID "${id}" is not an array`);
const newArr = arr.filter(d => !condition(d));
const data = this.#read();
data[id] = newArr;
this.#write(data);
return newArr;
}
add(id, number) {
this.#checkId(id);
const current = Number(this.#read()[id]) || 0;
const n = Number(number);
if (isNaN(n)) throw new TypeError(`Value "${number}" is not a number`);
const newVal = current + n;
this.set(id, newVal);
return newVal;
}
subtract(id, number) {
this.#checkId(id);
const current = Number(this.#read()[id]) || 0;
const n = Number(number);
if (isNaN(n)) throw new TypeError(`Value "${number}" is not a number`);
const newVal = current - n;
this.set(id, newVal);
return newVal;
}
#read() {
try {
const content = fs.readFileSync(this.path, "utf-8");
return JSON.parse(content);
} catch {
this.#write({});
return {};
}
}
#write(obj) {
fs.writeFileSync(this.path, JSON.stringify(obj, null, 2));
}
#checkId(id) {
if (!id) throw new TypeError("No ID specified");
if (typeof id !== "string") throw new TypeError(`ID "${id}" must be a string`);
}
}
module.exports = HomeDB;