pauladb
Version:
O uso de bancos de dados não relacionais é simples, permitindo a manipulação direta dos dados de maneira fácil.
63 lines (43 loc) • 1.92 kB
JavaScript
;
import { exec } from 'child_process';
import { existsSync } from 'fs';
import createSQL from 'better-sqlite3';
class PaulaDB {
constructor({ file = '.sqlitedata' } = {}) {
if (!existsSync(file)) exec('touch .sqlitedata'); /* <- verify the existence of a file -> */
this.file = file;
this.pauladb = 'PaulaDB'
this.database = new createSQL(this.file);
this.database.prepare(`CREATE TABLE IF NOT EXISTS ${this.pauladb} (key TEXT, value TEXT)`).run();
}
set(key, value) { /* <- sets the value (key, value) -> */
this._verifyKey(key);
this._verifyValue(value);
this.database.prepare(`INSERT INTO ${this.pauladb} (key, value) VALUES (?, ?)`).run(key, value);
return value;
}
get(key) { /* <- retrieve the value of a key -> */
this._verifyKey(key)
let value = this.database.prepare(`SELECT value FROM ${this.pauladb} WHERE key = ?`).get(key)?.value;
if (value == undefined) throw new Error('[NotFoundError] The passed key is undefined or invalid.')
return value;
}
all() { /* <- returns the array of the table -> */
const all = this.database.prepare(`SELECT * FROM ${this.pauladb}`).all();
if (all.length === 0) throw new Error('[NotFoundError] No data found in the database.')
return all;
}
delete(key) { /* <- delete a value from the table -> */
this._verifyKey(key)
const changes = this.database.prepare(`DELETE FROM ${this.pauladb} WHERE key = ?`).run(key).changes;
if (changes === 0) throw new Error('[NotFoundError] The passed key is undefined or invalid.');
return changes;
}
_verifyKey(key) { /* <- check the key -> */
if (!key) throw new Error("[KeyError] The provided key is not a valid string type.")
}
_verifyValue(value) { /* <- check the value -> */
if (!value) throw new Error("[ValueError] Invalid second value.")
}
}
export default PaulaDB;