upgrade.db
Version:
Banco de dados simples e leve em JSON para bots Node.js com suporte a tabelas e métodos modernos.
299 lines (238 loc) • 6.93 kB
JavaScript
const fs = require("fs");
const path = require("path");
class Table {
constructor(name = "default") {
this.name = name;
this.path = path.join(__dirname, `../db/${name}.json`);
if (!fs.existsSync(this.path)) fs.writeFileSync(this.path, "{}");
this.data = JSON.parse(fs.readFileSync(this.path, "utf8"));
}
save() {
fs.writeFileSync(this.path, JSON.stringify(this.data, null, 2));
}
set(key, value) {
this.data[key] = value;
this.save();
}
get(key) {
return this.data[key];
}
delete(key) {
delete this.data[key];
this.save();
}
has(key) {
return Object.prototype.hasOwnProperty.call(this.data, key);
}
push(key, value) {
if (!Array.isArray(this.data[key])) this.data[key] = [];
this.data[key].push(value);
this.save();
}
includes(key, value) {
if (!Array.isArray(this.data[key])) return false;
return this.data[key].includes(value);
}
add(key, value) {
let current = this.get(key);
if (typeof current !== "number") current = 0;
if (typeof value !== "number") throw new TypeError("Valor precisa ser número");
this.set(key, current + value);
}
subtract(key, value) {
let current = this.get(key);
if (typeof current !== "number") current = 0;
if (typeof value !== "number") throw new TypeError("Valor precisa ser número");
this.set(key, current - value);
}
math(key, operator, value) {
let current = this.get(key);
if (typeof current !== "number") current = 0;
if (typeof value !== "number") throw new TypeError("Valor precisa ser número");
switch (operator) {
case "+":
current += value;
break;
case "-":
current -= value;
break;
case "*":
current *= value;
break;
case "/":
if (value === 0) throw new Error("Divisão por zero");
current /= value;
break;
default:
throw new Error(`Operador inválido: ${operator}`);
}
this.set(key, current);
}
filter(callback) {
return Object.entries(this.data).filter(([key, val]) => callback(val, key));
}
find(callback) {
const found = Object.entries(this.data).find(([key, val]) => callback(val, key));
return found ? found[1] : undefined;
}
clear() {
this.data = {};
this.save();
}
keys() {
return Object.keys(this.data);
}
values() {
return Object.values(this.data);
}
entries() {
return Object.entries(this.data);
}
length() {
return Object.keys(this.data).length;
}
clone() {
return JSON.parse(JSON.stringify(this.data));
}
some(callback) {
return Object.entries(this.data).some(([key, val]) => callback(val, key));
}
every(callback) {
return Object.entries(this.data).every(([key, val]) => callback(val, key));
}
forEach(callback) {
Object.entries(this.data).forEach(([key, val]) => callback(val, key));
}
map(callback) {
return Object.entries(this.data).map(([key, val]) => callback(val, key));
}
random() {
const keys = this.keys();
if (keys.length === 0) return undefined;
const randKey = keys[Math.floor(Math.random() * keys.length)];
return this.data[randKey];
}
backup(filename = `${this.name}-backup.json`) {
const backupsDir = path.join(__dirname, "../backups");
if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true });
fs.writeFileSync(path.join(backupsDir, filename), JSON.stringify(this.data, null, 2));
}
export() {
return JSON.stringify(this.data);
}
import(jsonString) {
try {
const imported = JSON.parse(jsonString);
if (typeof imported === "object" && imported !== null) {
this.data = imported;
this.save();
return true;
}
return false;
} catch {
return false;
}
}
size() {
return Buffer.byteLength(JSON.stringify(this.data), "utf8");
}
increment(key) {
this.add(key, 1);
}
decrement(key) {
this.subtract(key, 1);
}
getType(key) {
const val = this.get(key);
if (val === null) return "null";
return typeof val;
}
merge(key, obj) {
if (typeof obj !== "object" || obj === null) throw new TypeError("Deve ser um objeto");
let current = this.get(key);
if (typeof current !== "object" || current === null) current = {};
const merged = { ...current, ...obj };
this.set(key, merged);
}
toggleBoolean(key) {
let current = this.get(key);
if (typeof current !== "boolean") current = false;
this.set(key, !current);
}
count() {
return this.length();
}
first() {
const keys = this.keys();
if (keys.length === 0) return undefined;
return this.data[keys[0]];
}
last() {
const keys = this.keys();
if (keys.length === 0) return undefined;
return this.data[keys[keys.length - 1]];
}
reverse() {
const entries = this.entries().reverse();
this.data = Object.fromEntries(entries);
this.save();
}
// Novos métodos adicionados
max(key, value, maxValue) {
if (typeof value !== "number") throw new TypeError("Valor precisa ser número");
if (typeof maxValue !== "number") throw new TypeError("maxValue precisa ser número");
let current = this.get(key);
if (typeof current !== "number") current = 0;
let newValue = current + value;
if (newValue > maxValue) newValue = maxValue;
this.set(key, newValue);
return newValue;
}
min(key, value, minValue) {
if (typeof value !== "number") throw new TypeError("Valor precisa ser número");
if (typeof minValue !== "number") throw new TypeError("minValue precisa ser número");
let current = this.get(key);
if (typeof current !== "number") current = 0;
let newValue = current - value;
if (newValue < minValue) newValue = minValue;
this.set(key, newValue);
return newValue;
}
reset(key, defaultValue = null) {
if (defaultValue === null) {
this.delete(key);
} else {
this.set(key, defaultValue);
}
}
clamp(key, minValue, maxValue) {
if (typeof minValue !== "number" || typeof maxValue !== "number")
throw new TypeError("minValue e maxValue precisam ser números");
if (minValue > maxValue) throw new Error("minValue não pode ser maior que maxValue");
let current = this.get(key);
if (typeof current !== "number") current = minValue;
if (current < minValue) current = minValue;
if (current > maxValue) current = maxValue;
this.set(key, current);
return current;
}
incrementBy(key, value = 1) {
this.add(key, value);
}
decrementBy(key, value = 1) {
this.subtract(key, value);
}
toArray() {
return Object.values(this.data);
}
toObject() {
return this.clone();
}
exists(key) {
return this.has(key);
}
remove(key) {
this.delete(key);
}
}
module.exports = Table;