-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.js
101 lines (86 loc) · 2.72 KB
/
storage.js
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
92
93
94
95
96
97
98
99
100
101
// IndexedDB storage service for conversation history
class ConversationStorage {
constructor() {
this.DB_NAME = 'conversationDB';
this.STORE_NAME = 'conversations';
this.VERSION = 1;
this.db = null;
}
async init() {
if (this.db) return;
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.DB_NAME, this.VERSION);
request.onerror = () => {
console.error('Failed to open database');
reject(request.error);
};
request.onsuccess = (event) => {
this.db = event.target.result;
resolve();
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.STORE_NAME)) {
db.createObjectStore(this.STORE_NAME, { keyPath: 'timestamp' });
}
};
});
}
async clearHistory() {
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.clear();
request.onsuccess = () => {
console.log('Conversation history cleared');
resolve();
};
request.onerror = () => {
console.error('Failed to clear history');
reject(request.error);
};
});
}
async addEntry(entry) {
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
const enhancedEntry = {
...entry,
timestamp: Date.now()
};
const request = store.add(enhancedEntry);
request.onsuccess = () => {
console.log('Entry added to history');
resolve();
};
request.onerror = () => {
console.error('Failed to add entry');
reject(request.error);
};
});
}
async getAllHistory() {
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.getAll();
request.onsuccess = () => {
// Sort by timestamp and remove timestamp from returned objects
const history = request.result
.sort((a, b) => a.timestamp - b.timestamp)
.map(({ timestamp, ...entry }) => entry);
resolve(history);
};
request.onerror = () => {
console.error('Failed to get history');
reject(request.error);
};
});
}
}
// Export singleton instance
export const conversationStorage = new ConversationStorage();