qjson-db
Version:
Lightweight local JSON-based database for Node.js projects.
154 lines (153 loc) • 5.07 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var index_exports = {};
__export(index_exports, {
JSONdb: () => JSONdb,
default: () => index_default
});
module.exports = __toCommonJS(index_exports);
var import_fs = __toESM(require("fs"), 1);
var import_path = __toESM(require("path"), 1);
const defaultOptions = {
asyncWrite: false,
syncOnWrite: true,
jsonSpaces: 4,
stringify: JSON.stringify,
parse: JSON.parse
};
function validateJSON(fileContent, options) {
try {
options.parse(fileContent);
} catch (e) {
console.error("The specified file is not empty and does not contain valid JSON.");
throw e;
}
return true;
}
class JSONdb {
/**
* @param {string} filePath
* @param {object} [options]
*/
constructor(filePath, options = {}) {
if (typeof filePath !== "string") {
throw new Error("Invalid file path.");
}
this.filePath = filePath.endsWith(".json") ? filePath : `${filePath}.json`;
this.options = { ...defaultOptions, ...options };
this.storage = {};
const directory = import_path.default.dirname(this.filePath);
if (!import_fs.default.existsSync(directory)) {
import_fs.default.mkdirSync(directory, { recursive: true });
}
let stats;
try {
stats = import_fs.default.statSync(this.filePath);
} catch (err) {
if (err.code === "ENOENT") {
return;
} else if (err.code === "EACCES") {
throw new Error(`Cannot access path "${this.filePath}".`);
} else {
throw new Error(`Error checking path "${this.filePath}": ${err}`);
}
}
try {
import_fs.default.accessSync(this.filePath, import_fs.default.constants.R_OK | import_fs.default.constants.W_OK);
} catch (err) {
throw new Error(`Cannot read/write at "${this.filePath}". Check permissions!`);
}
if (stats.size > 0) {
const data = import_fs.default.readFileSync(this.filePath, "utf-8");
if (validateJSON(data, this.options)) {
this.storage = this.options.parse(data);
}
}
}
init(key, value) {
if (!this.storage.hasOwnProperty(key)) {
this.storage[key] = value;
if (this.options.syncOnWrite) this.sync();
}
}
set(key, value) {
this.storage[key] = value;
if (this.options.syncOnWrite) this.sync();
}
get(key) {
return this.storage.hasOwnProperty(key) ? this.storage[key] : void 0;
}
has(key) {
return this.storage.hasOwnProperty(key);
}
delete(key) {
const retVal = this.storage.hasOwnProperty(key) ? delete this.storage[key] : void 0;
if (this.options.syncOnWrite) this.sync();
return retVal;
}
deleteAll() {
for (const key in this.storage) {
this.delete(key);
}
return this;
}
sync() {
const json = this.options.stringify(this.storage, null, this.options.jsonSpaces);
if (this.options.asyncWrite) {
import_fs.default.writeFile(this.filePath, json, (err) => {
if (err) throw err;
});
} else {
try {
import_fs.default.writeFileSync(this.filePath, json);
} catch (err) {
if (err.code === "EACCES") {
throw new Error(`Cannot access path "${this.filePath}".`);
} else {
throw new Error(`Write error at "${this.filePath}": ${err}`);
}
}
}
}
JSON(storage) {
if (storage) {
try {
JSON.parse(this.options.stringify(storage));
this.storage = storage;
} catch (err) {
throw new Error("Provided value is not a valid JSON object.");
}
}
return JSON.parse(this.options.stringify(this.storage));
}
}
var index_default = JSONdb;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
JSONdb
});