-
Notifications
You must be signed in to change notification settings - Fork 12
/
db.js
210 lines (178 loc) · 8.03 KB
/
db.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
class Gallery {
constructor(dbName, version = 1) {
this.dbName = dbName;
this.version = version;
this.db = null;
this.ITEMS_PER_PAGE = 12;
}
async init() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, this.version);
request.onupgradeneeded = (event) => {
this.db = event.target.result;
if (!this.db.objectStoreNames.contains('galleries')) {
const objectStore = this.db.createObjectStore('galleries', { keyPath: 'id', autoIncrement: true });
objectStore.createIndex('collectionName', 'collectionName', { unique: false });
objectStore.createIndex('imageName', 'imageName', { unique: false });
objectStore.createIndex('imageTags', 'imageTags', { unique: false });
objectStore.createIndex('imageData', 'imageData', { unique: false });
}
};
request.onsuccess = (event) => {
this.db = event.target.result;
// Check if 'galleries' object store exists
if (!this.db.objectStoreNames.contains('galleries')) {
// If it doesn't exist, close the database and increment the version
this.db.close();
this.version++;
this.init().then(resolve).catch(reject);
} else {
resolve();
}
};
request.onerror = (event) => {
reject(`IndexedDB error: ${event.target.errorCode}`);
};
});
}
async addImage(collectionName, imageName, imageTags, imageData) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['galleries'], 'readwrite');
const objectStore = transaction.objectStore('galleries');
const newImage = { collectionName, imageName, imageTags, imageData };
const request = objectStore.add(newImage);
request.onsuccess = () => resolve();
request.onerror = (event) => reject(`Error adding image: ${event.target.errorCode}`);
});
}
async getGalleryItems(page, selectedCollection) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['galleries'], 'readonly');
const objectStore = transaction.objectStore('galleries');
const getAllRequest = objectStore.getAll();
getAllRequest.onsuccess = () => {
let allItems = getAllRequest.result;
// Filter items if a collection is selected
if (selectedCollection) {
allItems = allItems.filter(item => item.collectionName === selectedCollection);
}
const totalItems = allItems.length;
const totalPages = Math.ceil(totalItems / this.ITEMS_PER_PAGE);
const start = (page - 1) * this.ITEMS_PER_PAGE;
const end = start + this.ITEMS_PER_PAGE;
const results = allItems.slice(start, end);
resolve({ results, totalPages, currentPage: page });
};
getAllRequest.onerror = (event) => reject(`Error loading gallery: ${event.target.errorCode}`);
});
}
async deleteImage(id) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['galleries'], 'readwrite');
const objectStore = transaction.objectStore('galleries');
const request = objectStore.delete(id);
request.onsuccess = () => resolve();
request.onerror = (event) => reject(`Error deleting image: ${event.target.errorCode}`);
});
}
async getCollectionNames() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['galleries'], 'readonly');
const objectStore = transaction.objectStore('galleries');
const request = objectStore.getAll();
request.onsuccess = (event) => {
const allImages = event.target.result;
const collectionNames = [...new Set(allImages.map(image => image.collectionName))];
resolve(collectionNames);
};
request.onerror = (event) => reject(`Error fetching collection names: ${event.target.errorCode}`);
});
}
async exportGallery() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['galleries'], 'readonly');
const objectStore = transaction.objectStore('galleries');
const request = objectStore.getAll();
request.onsuccess = (event) => {
const allImages = event.target.result;
resolve(JSON.stringify(allImages));
};
request.onerror = (event) => reject(`Error exporting gallery: ${event.target.errorCode}`);
});
}
async importFromFile(filePath) {
try {
const response = await fetch(filePath);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const jsonData = await response.json();
return this.importGallery(jsonData);
} catch (error) {
console.error('Error importing from file:', error);
throw error;
}
}
async importGallery(importedData) {
return new Promise((resolve, reject) => {
if (!Array.isArray(importedData)) {
reject(new Error('Invalid import data format'));
return;
}
const transaction = this.db.transaction(['galleries'], 'readwrite');
const objectStore = transaction.objectStore('galleries');
let successCount = 0;
let errorCount = 0;
importedData.forEach((item) => {
if (this.validateImportItem(item)) {
const request = objectStore.add(item);
request.onsuccess = () => {
successCount++;
if (successCount + errorCount === importedData.length) {
resolve({ successCount, errorCount });
}
};
request.onerror = () => {
errorCount++;
if (successCount + errorCount === importedData.length) {
resolve({ successCount, errorCount });
}
};
} else {
errorCount++;
if (successCount + errorCount === importedData.length) {
resolve({ successCount, errorCount });
}
}
});
});
}
validateImportItem(item) {
return (
item &&
typeof item.collectionName === 'string' &&
typeof item.imageName === 'string' &&
typeof item.imageTags === 'string' &&
typeof item.imageData === 'string' &&
item.imageData.startsWith('data:image/')
);
}
async getRandomImage() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['galleries'], 'readonly');
const objectStore = transaction.objectStore('galleries');
const request = objectStore.getAll();
request.onsuccess = (event) => {
const allImages = event.target.result;
if (allImages.length > 0) {
const randomIndex = Math.floor(Math.random() * allImages.length);
resolve(allImages[randomIndex]);
} else {
resolve(null);
}
};
request.onerror = (event) => reject(`Error fetching random image: ${event.target.errorCode}`);
});
}
}
export default Gallery;