evils.db
Version:
  
74 lines (73 loc) • 2.44 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BsonDatabase = 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 BsonDatabase extends Database_1.Database {
constructor(options) {
super();
Object.defineProperty(this, "options", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "bson", {
enumerable: true,
configurable: true,
writable: true,
value: undefined
});
this.options = options;
try {
this.bson = require('bson');
}
catch {
throw new Error_1.DatabaseError('The "bson" module is not installed. Please install it with "npm install bson"');
}
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, this.bson.serialize(this.cache));
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, this.bson.serialize(this.cache));
return value;
}
clear() {
this.cache = {};
(0, fs_1.writeFileSync)(this.options.filePath, this.bson.serialize(this.cache));
return this.cache;
}
has(key) {
return (0, lodash_1.has)(this.cache, key);
}
get size() {
return Object.keys(this.cache).length;
}
get filePath() {
return this.options.filePath;
}
}
exports.BsonDatabase = BsonDatabase;