@glimpsrc/clouddb
Version:
A cloudDB, uma database poderosa e simples para seus projetos pessoais!
97 lines (80 loc) • 2.21 kB
JavaScript
import fs from 'fs/promises';
import path from 'path';
export class CloudDB {
constructor(filePath = 'db.json', options = {}) {
this.filePath = path.resolve(filePath);
this.encoding = options.encoding || 'utf-8';
this.autoSave = options.autoSave ?? true;
this.mode = options.mode || 'json'; // 'json' ou 'text'
this.db = this.mode === 'json' ? {} : ''; // Inicialização
}
async init() {
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
await this.reload();
}
async _save() {
const data = this.mode === 'json'
? JSON.stringify(this.db, null, 2)
: this.db.toString();
await fs.writeFile(this.filePath, data, this.encoding);
}
async reload() {
try {
const data = await fs.readFile(this.filePath, this.encoding);
this.db = this.mode === 'json' ? JSON.parse(data) : data;
} catch {
this.db = this.mode === 'json' ? {} : '';
await this._save();
}
}
// JSON MODE
async get(key) {
if (this.mode !== 'json') return null;
return this.db[key];
}
async set(key, value) {
if (this.mode !== 'json') return;
this.db[key] = value;
if (this.autoSave) await this._save();
}
async delete(key) {
if (this.mode !== 'json') return;
delete this.db[key];
if (this.autoSave) await this._save();
}
async has(key) {
if (this.mode !== 'json') return false;
return Object.prototype.hasOwnProperty.call(this.db, key);
}
async keys() {
if (this.mode !== 'json') return [];
return Object.keys(this.db);
}
async values() {
if (this.mode !== 'json') return [];
return Object.values(this.db);
}
async all() {
return this.mode === 'json' ? { ...this.db } : this.db;
}
async clear() {
this.db = this.mode === 'json' ? {} : '';
if (this.autoSave) await this._save();
}
async save() {
await this._save();
}
async size() {
return this.mode === 'json'
? Object.keys(this.db).length
: this.db.length;
}
getPath() {
return this.filePath;
}
toJSON() {
return this.mode === 'json'
? JSON.stringify(this.db, null, 2)
: JSON.stringify({ content: this.db });
}
}