UNPKG

evils.db

Version:

![Image](https://img.shields.io/npm/v/evils.db) ![Image](https://img.shields.io/npm/dt/evils.db) ![Image](https://nodei.co/npm/evils.db.png)

122 lines (121 loc) 3.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonDatabase = void 0; const fs_1 = require("fs"); const lodash_1 = require("lodash"); const path_1 = require("path"); const Database_1 = require("./Database"); const Error_1 = require("./Error"); class JsonDatabase extends Database_1.Database { constructor(options) { super(); Object.defineProperty(this, "options", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "json", { enumerable: true, configurable: true, writable: true, value: undefined }); this.options = options; try { this.json = require('json'); } catch { throw new Error_1.DatabaseError('The "json" module is not installed. Please install it with "npm install json"'); } const resolvedFilePath = process.cwd(); const filePath = resolvedFilePath + path_1.sep + this.options.filePath; const paths = this.options.filePath.split(path_1.sep); for (const path of paths) { const resolvedPath = resolvedFilePath + path_1.sep + path; if (!(0, fs_1.existsSync)(resolvedPath)) { (0, fs_1.writeFileSync)(resolvedPath, ''); } } } set(key, value) { (0, lodash_1.set)(this.cache, key, value); (0, fs_1.writeFileSync)(this.options.filePath, JSON.stringify(this.cache, null, 1 ?? 4)); return value; } get(key) { return (0, lodash_1.get)(this.cache, key); } getAll() { return this.cache; } delete(key) { const value = (0, lodash_1.get)(this.cache, key); delete this.cache[key]; (0, fs_1.writeFileSync)(this.options.filePath, JSON.stringify(this.cache, null, 1 ?? 4)); return value; } clear() { this.cache = {}; (0, fs_1.writeFileSync)(this.options.filePath, JSON.stringify(this.cache, null, 1 ?? 4)); return this.cache; } has(key) { return (0, lodash_1.has)(this.cache, key); } add(key, value) { if (!this.has(key)) { this.set(key, value); return value; } const data = this.get(key); const added = data + value; this.set(key, added); return added; } subtract(key, value) { if (!this.has(key)) { this.set(key, value); return value; } const data = this.get(key); const subtracted = data - value; this.set(key, subtracted); return subtracted; } push(key, value) { if (!this.has(key)) { this.set(key, [value]); return [value]; } const data = this.get(key); data.push(value); this.set(key, data); return data; } pull(key, value) { if (!this.has(key)) { this.set(key, [value]); return [value]; } const data = this.get(key); const index = data.indexOf(value); if (index > -1) { data.splice(index, 1); } this.set(key, data); return data; } includes(key, value) { if (!this.has(key)) { this.set(key, [value]); return false; } const data = this.get(key); return data.includes(value); } get size() { return Object.keys(this.cache).length; } } exports.JsonDatabase = JsonDatabase;