UNPKG

datanautics

Version:

**Datanautics** is a lightweight key-value storage system with support for nested property access, persistent dumps to disk, and configurable autosave intervals.

74 lines 2.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Datanautics = void 0; const events_1 = require("events"); const fs_1 = require("fs"); const property_accessor_1 = require("property-accessor"); const _const_1 = require("./constants"); class Datanautics { options; data; eventEmitter; constructor(options) { this.options = Object.assign(_const_1.defaultDatanauticsOptions, options || {}); this.data = {}; this.eventEmitter = new events_1.EventEmitter(); if ((0, fs_1.existsSync)(this.options.dumpPath)) { this.useDump(); } this.eventEmitter.on(_const_1.DUMP_EVENT, async () => { this.createDump(); setTimeout(() => { this.eventEmitter.emit(_const_1.DUMP_EVENT); }, this.options.dumpInterval); }); this.eventEmitter.emit(_const_1.DUMP_EVENT); } store() { return this.createDump(); } createDump() { try { const flat = property_accessor_1.PropertyAccessor.flat(this.data); const data = []; for (const key in flat) { const value = property_accessor_1.PropertyAccessor.get(key, this.data); if (value !== undefined) { data.push(`${key} ${value.toString()}`); } } (0, fs_1.writeFileSync)(this.options.dumpPath, data.join('\n'), 'utf8'); } catch (e) { if (this.options.verbose) { this.options.logger.error(e); } } } useDump() { const data = (0, fs_1.readFileSync)(this.options.dumpPath).toString('utf8'); const lines = data.split('\n'); for (const line of lines) { const [k, v] = line.split(' '); const key = k.trim(); if (v !== undefined) { let value = v.trim(); if (/^[+-]?\d+(\.\d+)?$/.test(value)) { value = /^[+-]?\d+$/.test(value) ? parseInt(value, 10) : parseFloat(value); } else if (/^false|true$/.test(value)) { value = /^true$/.test(value); } property_accessor_1.PropertyAccessor.set(key, value, this.data); } } } set(key, value) { return property_accessor_1.PropertyAccessor.set(key, value, this.data); } get(key) { return property_accessor_1.PropertyAccessor.get(key, this.data); } } exports.Datanautics = Datanautics; //# sourceMappingURL=datanautics.js.map