mxtorie-db
Version:
Create database easily
221 lines (194 loc) • 6.4 kB
JavaScript
const { privateDecrypt } = require("crypto");
const fs = require("fs");
const { fileURLToPath } = require("url");
const setNestedProperty = (object, key, value) => {
const properties = key.split('.');
//console.log(properties)
let index = 0;
for (; index < properties.length - 1; ++index) {
object = object[properties[index]];
}
object[properties[index]] = value;
}
const getNestedProperty = (object, key) => {
const properties = key.split('.');
let index = 0;
for (; index < properties.length; ++index) {
object = object && object[properties[index]];
}
return object;
}
module.exports = class mxtorieDB {
/**
* @typedef {object} BackupsOptions
* @property {boolean} [enabled=false] Whether the backups are enabled
* @property {number} [interval=86400000] The interval between each backup
* @property {string} [path='./backups/'] The path of the backups
*/
/**
* @typedef {object} DatabaseOptions
* @property {BackupsOptions} backup
* @property {object} preset
*/
/**
* @param {string} filePath The path of the json file used for the database.
* @param {DatabaseOptions} options
*/
constructor(filePath, options){
/**
* Path of the json file
* @type {string}
*/
this.jsonFilePath = filePath || "./mxtorie.json"
/**
* Options of the database
* @type {MxtorieOptions}
*/
this.options = options || {}
if (this.options.backup && this.options.backup.enabled) {
const path = this.options.backup.path || './backups/';
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
setInterval(() => {
this.makeSnapshot();
}, (this.options.backup.interval || 86400000));
}
/**
* The data stored in the database.
* @type {object}
*/
this.data = {};
if(!fs.existsSync(this.jsonFilePath)){
if(!this.options.preset || typeof this.options.preset!="object"){
fs.writeFileSync(this.jsonFilePath, "{}", "utf-8");
} else {
this.data = this.options.preset
fs.writeFileSync(this.jsonFilePath, JSON.stringify(this.data, null, 2), "utf-8")
}
} else {
this.fetchDataFromFile();
}
}
/**
* Make a backup of the database
* @param {string} path The path where the backup will be stored
*/
makeSnapshot (path) {
path = path || this.options.backup.path || './backups/';
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
const fileName = `backup-${Date.now()}.json`;
fs.writeFileSync(path.join(path, fileName));
}
/**
* Get data from the file and store it in the data property.
*/
fetchDataFromFile(){
const savedData = JSON.parse(fs.readFileSync(this.jsonFilePath));
if(typeof savedData === "object"){
this.data = savedData;
}
}
/**
* Write data to the file.
*/
saveDataToFile(){
fs.writeFileSync(this.jsonFilePath, JSON.stringify(this.data, null, 2), "utf-8");
}
/**
* Get data for a key in the database
* @param {string} key
*/
get(key){
return getNestedProperty(this.data, key);
}
/**
* Check if a key data exists.
* @param {string} key
*/
has(key){
return Boolean(getNestedProperty(this.data, key));
}
/**
* Set new data for a key in the database.
* @param {string} key
* @param {*} value
*/
set(key, value){
if(key.includes(" ") || !key || key=="") return SyntaxError("Key can't be null or contain a space.")
setNestedProperty(this.data, key, value);
this.saveDataToFile();
}
/**
* Delete data for a key from the database.
* @param {string} key
*/
delete(key){
delete this.data[key];
this.saveDataToFile();
}
tempo(key, value, time){
if(key.includes(" ") || !key || key=="") return SyntaxError("Key can't be null or contain a space.")
if(!time || isNaN(time)) return SyntaxError("The time need to be a number. (ms)")
setNestedProperty(this.data, key, value);
this.saveDataToFile();
setTimeout(()=>{
delete this.data[key];
}, time)
}
/**
* Add a number to a key in the database.
* @param {string} key
* @param {number} count
*/
add(key, count){
if(key.includes(" ") || !key || key=="") return SyntaxError("Key can't be null or contain a space.")
if(isNaN(count)) return SyntaxError("The value is NaN.")
if(!this.data[key]) this.data[key] = 0;
this.data[key] += count;
this.saveDataToFile();
}
/**
* Subtract a number to a key in the database.
* @param {string} key
* @param {number} count
*/
subtract(key, count){
if(key.includes(" ") || !key || key=="") return SyntaxError("Key can't be null or contain a space.")
if(isNaN(count)) return SyntaxError("The value is NaN.")
if(!this.data[key]) this.data[key] = 0;
this.data[key] -= count;
this.saveDataToFile();
}
/**
* Push an element to a key in the database.
* @param {string} key
* @param {*} element
*/
push(key, element){
if(key.includes(" ") || !key || key=="") return SyntaxError("Key can't be null or contain a space.")
if (!this.data[key]) this.data[key] = [];
this.data[key].push(element);
this.saveDataToFile();
}
/**
* Clear EVERYTHINGS the database.
*/
clear(){
this.data = {};
this.saveDataToFile();
}
/**
* Get all the data from the database.
*/
all(){
return Object.keys(this.data).map((key) => {
return {
key,
data: this.data[key]
}
});
}
}