...
 
Commits (2)
{
"name": "@creanet/js-db",
"version": "2.4.0",
"version": "2.4.1",
"description": "Used for communication between NodeJS and PostgreSQL",
"main": "index.js",
"scripts": {
......
......@@ -22,6 +22,16 @@ class Database {
*/
constructor({ host, port, database, user, password }) {
this._db = new Pool({ host, port, database, user, password });
this._transaction = false;
}
/**
* Returns `true` if a transaction is active; `false` otherwise
*
* @readonly
*/
get transaction() {
return this._transaction;
}
/**
......@@ -75,6 +85,36 @@ class Database {
update(table) {
return new Update(this, table);
}
/**
* Begins a transaction
*
* @returns {Promise.<Boolean>} success
*/
begin() {
if (this._transaction) {
throw new Error('A transaction is already active');
}
return this.query('BEGIN')
.execute()
.then(() => (this._transaction = true));
}
/**
* Commits an active transaction
*
* @returns {Promise.<Boolean>} success
*/
commit() {
if (!this._transaction) {
throw new Error('No transaction is active');
}
return this.query('COMMIT')
.execute()
.then(() => (this._transaction = false));
}
}
module.exports = Database;
......@@ -46,6 +46,8 @@ const del = async () => {
};
const update = async () => {
await db.begin();
console.log('UPDATE');
const update = db
.update('lorem')
......@@ -58,6 +60,8 @@ const update = async () => {
} else {
console.log(update.err);
}
await db.commit();
};
(async () => {
......