Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import * as Objection from 'objection';
  2.  
  3. export class TransactionManager {
  4.  
  5. private knex = null;
  6. public transaction: Objection.Transaction = null;
  7. private nestingLevel: number = 0;
  8. private isRollbackOnly: boolean = false;
  9.  
  10. constructor() {
  11. this.knex = Objection.Model.knex();
  12. }
  13.  
  14. public async begin()
  15. {
  16. this.nestingLevel++;
  17.  
  18. if(this.nestingLevel === 1) {
  19. this.transaction = await Objection.transaction.start(this.knex);
  20. }
  21. }
  22.  
  23. public async commit()
  24. {
  25. if(this.isRollbackOnly)
  26. throw new Error('Cannot commit - transaction is rollback only');
  27.  
  28. if(this.nestingLevel === 0)
  29. throw new Error('Cannot commit - no active transaction');
  30.  
  31. if(this.nestingLevel === 1) {
  32. await this.transaction.commit();
  33. }
  34.  
  35. --this.nestingLevel;
  36. }
  37.  
  38. public async rollback()
  39. {
  40. if(this.nestingLevel === 0)
  41. throw new Error('Cannot commit - no active transaction');
  42.  
  43. if(this.nestingLevel === 1) {
  44. await this.transaction.rollback();
  45. }
  46. else {
  47. this.isRollbackOnly = true;
  48. }
  49.  
  50. --this.nestingLevel;
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement