-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdatabase.js
58 lines (48 loc) · 1.69 KB
/
database.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
// let database
const initializeDb = indexedDB.open('instagram', 1)
// initializeDb.onsuccess = () => {
// database = initializeDb.result
// console.log('Success creating or accessing db')
// }
initializeDb.onupgradeneeded = () => {
const database = initializeDb.result
database.createObjectStore('bio', {autoIncrement: true})
database.createObjectStore('gallery', {autoIncrement: true})
}
initializeDb.onerror = () => {
alert('Error creating or accessing db')
}
const addEntryToDb = (storeName, entry) => {
const database = initializeDb.result
const transaction = database.transaction([storeName], 'readwrite')
const store = transaction.objectStore(storeName)
store.add(entry)
// transaction.oncomplete = () => alert(`Entry added to ${storeName}!`)
transaction.onerror = () => {
console.log(`error adding Entry to ${storeName}.`)
console.log(transaction.error);
}
}
const getEntryFromDb = (storeName, id) => {
const data = new Promise((resolve, reject) => {
const database = initializeDb.result
const transaction = database.transaction([storeName])
const store = transaction.objectStore(storeName)
const request = id ? store.get(id) : store.getAll()
request.onerror = () => {
reject(request.error)
console.log('error getting data from the store');
}
request.onsuccess = () => {
resolve(request.result)
}
})
return Promise.resolve(data)
}
const clearAllEntries = (storeName) => {
const database = initializeDb.result
const transaction = database.transaction([storeName], 'readwrite')
const store = transaction.objectStore(storeName)
store.clear()
}
export { initializeDb, addEntryToDb, getEntryFromDb, clearAllEntries }