Skip to content
This repository has been archived by the owner on Sep 12, 2023. It is now read-only.

Commit

Permalink
refactor(database): ensure transaction is initialized
Browse files Browse the repository at this point in the history
  • Loading branch information
KennethTrecy committed Sep 12, 2022
1 parent 86510ef commit 3e7f57f
Showing 1 changed file with 30 additions and 20 deletions.
50 changes: 30 additions & 20 deletions database/managers/helpers/transaction_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@ import { Transaction } from "sequelize"

import Log from "$!/singletons/log"
import Database from "%/data_source/database"
import DatabaseError from "$!/errors/database"

/**
* Manages the transaction to be implementation-agnostic
*/
export default class {
private transaction: Transaction|null = null
private rawTransaction: Transaction|null = null

async initialize() {
if (this.transaction === null && this.isPermitted) {
// For informred decision, please read:
// https://medium.com/nerd-for-tech/understanding-database-isolation-levels-c4ebcd55c6b9
this.transaction = await Database.dataSource.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
if (this.rawTransaction === null && this.isPermitted) {
/*
* For informred decision, please read:
* https://medium.com/nerd-for-tech/understanding-database-isolation-levels-c4ebcd55c6b9
*/
this.rawTransaction = await Database.dataSource.transaction({
"isolationLevel": Transaction.ISOLATION_LEVELS.READ_COMMITTED
})

Log.success("transaction", "initialized database transaction")
Expand All @@ -24,44 +27,51 @@ export default class {
get transactionObject(): { transaction?: Transaction } {
if (this.hasDestroyed || !this.isPermitted) {
return {}
} else {
return {
transaction: this.transaction!
}
}
return {
"transaction": this.transaction
}
}

get lockedTransactionObject(): { lock?: boolean, transaction?: Transaction } {
if (this.hasDestroyed || !this.isPermitted) {
return {}
} else {
return {
lock: true,
...this.transactionObject
}
}

return {
"lock": true,
...this.transactionObject
}
}

async destroySuccessfully() {
if (this.mayDestroy) {
await this.transaction!.commit()
this.transaction = null
await this.transaction.commit()
this.rawTransaction = null

Log.success("transaction", "committed the database changes")
}
}

async destroyIneffectually() {
if (this.mayDestroy) {
await this.transaction!.rollback()
this.transaction = null
await this.transaction.rollback()
this.rawTransaction = null

Log.success("transaction", "rolled back the database changes")
}
}

get hasDestroyed(): boolean {
return this.transaction === null
return this.rawTransaction === null
}

private get transaction(): Transaction {
if (this.hasDestroyed) {
throw new DatabaseError("Transaction is not initiated.")
}

return this.transaction
}

private get mayDestroy(): boolean {
Expand Down

0 comments on commit 3e7f57f

Please sign in to comment.