Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as Objection from 'objection';
- export class TransactionManager {
- private knex = null;
- public transaction: Objection.Transaction = null;
- private nestingLevel: number = 0;
- private isRollbackOnly: boolean = false;
- constructor() {
- this.knex = Objection.Model.knex();
- }
- public async begin()
- {
- this.nestingLevel++;
- if(this.nestingLevel === 1) {
- this.transaction = await Objection.transaction.start(this.knex);
- }
- }
- public async commit()
- {
- if(this.isRollbackOnly)
- throw new Error('Cannot commit - transaction is rollback only');
- if(this.nestingLevel === 0)
- throw new Error('Cannot commit - no active transaction');
- if(this.nestingLevel === 1) {
- await this.transaction.commit();
- }
- --this.nestingLevel;
- }
- public async rollback()
- {
- if(this.nestingLevel === 0)
- throw new Error('Cannot commit - no active transaction');
- if(this.nestingLevel === 1) {
- await this.transaction.rollback();
- }
- else {
- this.isRollbackOnly = true;
- }
- --this.nestingLevel;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement