File size: 1,406 Bytes
0bfe2e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { createLogger } from '../utils';
import { DB } from './db';
const logger = createLogger('db');
const db = DB.getInstance();

// Queue for SQLite transactions

export class TransactionQueue {
  private queue: Array<() => Promise<any>> = [];
  private processing = false;
  private static instance: TransactionQueue;

  private constructor() {}

  static getInstance(): TransactionQueue {
    if (!this.instance) {
      this.instance = new TransactionQueue();
    }
    return this.instance;
  }

  async enqueue<T>(operation: () => Promise<T>): Promise<T> {
    // If using PostgreSQL, execute directly without queuing
    if (db['uri']?.dialect === 'postgres') {
      return operation();
    }

    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try {
          const result = await operation();
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });
      this.processQueue();
    });
  }

  private async processQueue() {
    if (this.processing || this.queue.length === 0) return;
    this.processing = true;

    while (this.queue.length > 0) {
      const operation = this.queue.shift();
      if (operation) {
        try {
          await operation();
        } catch (error) {
          logger.error('Error processing queued operation:', error);
        }
      }
    }

    this.processing = false;
  }
}