File size: 2,103 Bytes
f0efd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Phase 7: Sync Queue
// Handles persistent queueing of document changes for offline support

const QUEUE_KEY = 'bayan_sync_queue';

const SyncQueue = {
  /**
   * Get all pending items in the queue
   * @returns {Array<{id: string, docId: string, content: string, timestamp: number, retries: number}>}
   */
  getAll() {
    try {
      const data = localStorage.getItem(QUEUE_KEY);
      return data ? JSON.parse(data) : [];
    } catch (e) {
      console.warn('Failed to read sync queue', e);
      return [];
    }
  },

  /**
   * Save the entire queue
   * @param {Array} queue 
   */
  _save(queue) {
    try {
      localStorage.setItem(QUEUE_KEY, JSON.stringify(queue));
    } catch (e) {
      console.warn('Failed to save sync queue', e);
    }
  },

  /**
   * Add a new change to the queue, replacing any existing pending change for the same doc
   * @param {string} docId 
   * @param {string} content 
   */
  enqueue(docId, content) {
    if (!docId) return;
    const queue = this.getAll();
    
    // Remove existing entry for the same doc to prevent duplicate redundant writes
    const filteredQueue = queue.filter(item => item.docId !== docId);
    
    filteredQueue.push({
      id: Date.now().toString() + '_' + Math.random().toString(36).substr(2, 5),
      docId,
      content,
      timestamp: Date.now(),
      retries: 0
    });

    this._save(filteredQueue);
  },

  /**
   * Remove a specific item from the queue after successful sync
   * @param {string} id 
   */
  remove(id) {
    const queue = this.getAll().filter(item => item.id !== id);
    this._save(queue);
  },

  /**
   * Increment retry count for a failed sync attempt
   * @param {string} id 
   */
  incrementRetry(id) {
    const queue = this.getAll();
    const item = queue.find(i => i.id === id);
    if (item) {
      item.retries += 1;
      this._save(queue);
    }
  },

  /**
   * Clear the entire queue
   */
  clear() {
    try {
      localStorage.removeItem(QUEUE_KEY);
    } catch (e) {}
  }
};

if (typeof module !== 'undefined' && module.exports) {
  module.exports = { SyncQueue };
}