json-file-database
Version:
Lightweight Database on NodeJS by JSON Files
77 lines (76 loc) • 2.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.connect = void 0;
const collection_1 = require("./collection");
const database_file_1 = require("./database-file");
function getDataSaver(data, delay, file, beautify, onSaved) {
let timeout;
return (name, elements) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
data[name] = elements;
file.write(JSON.stringify(data, null, beautify ? 2 : 0));
onSaved.apply(undefined);
}, delay);
};
}
function withDefaults(data, defaults) {
return Object.keys(defaults).reduce((data, key) => {
var _a;
const data1 = data;
const defaults1 = defaults;
(_a = data1[key]) !== null && _a !== void 0 ? _a : (data1[key] = defaults1[key]);
return data;
}, data);
}
function createDatabase(data, save) {
return (options) => {
// Make options with default values.
const { name, comparator, primaryKey } = withDefaults(options, {
comparator: (first, second) => {
first = Reflect.get(first, primaryKey);
second = Reflect.get(second, primaryKey);
if (first > second)
return 1;
else if (first < second)
return -1;
return 0;
},
});
// Make sure the property is an array.
const elements = data[name] || (data[name] = []);
if (!Array.isArray(elements))
throw new TypeError(`Property ${name} in the database is not an array.`);
// Make collection options.
return new collection_1.Collection({ name, comparator, primaryKey, elements, save });
};
}
/**
* Connects the database synchronously.
* @param options the options for connection.
* @returns the database.
*/
function connect(options) {
// Make the options with default values.
const op = withDefaults(options, {
beautify: false,
delay: 0,
init: {},
onSaved: () => { },
});
const { beautify, delay, init, onSaved } = op;
let { file } = op;
if (typeof file === 'string')
file = (0, database_file_1.createFile)(file);
// Read the file, or set the data as init.
let data;
try {
data = JSON.parse(file.read());
}
catch (_a) {
data = init;
}
const save = getDataSaver(data, delay, file, beautify, onSaved);
return createDatabase(data, save);
}
exports.connect = connect;