Notes2/static/js/node_store.mjs
Magnus Åhall 5c2842c995 wip
2024-11-30 17:10:46 +01:00

88 lines
2.1 KiB
JavaScript

export class NodeStore {
constructor() {
if (!('indexedDB' in window)) {
throw 'Missing IndexedDB'
}
this.db = null
}
async initializeDB() {
return new Promise((resolve, reject) => {
let req = indexedDB.open('notes', 2)
// Schema upgrades for IndexedDB.
// These can start from different points depending on updates to Notes2 since a device was online.
req.onupgradeneeded = (event) => {
var store
let db = event.target.result
let trx = event.target.transaction
for (let i = event.oldVersion + 1; i <= event.newVersion; i++) {
console.log(`Upgrade to schema ${i}`)
// The schema transformations.
switch (i) {
case 1:
store = db.createObjectStore('nodes', { keyPath: 'ID' })
store.createIndex('nameIndex', 'Name', { unique: false })
break
case 2:
trx.objectStore('nodes').createIndex('parentIndex', 'ParentID', { unique: false })
break
}
}
}
req.onsuccess = (event) => {
this.db = event.target.result
resolve()
}
req.onerror = (event) => {
reject(event.target.error)
}
})
}
async add(records) {
return new Promise((resolve, reject) => {
try {
let t = this.db.transaction('nodes', 'readwrite')
let nodeStore = t.objectStore('nodes')
t.onerror = (event) => {
console.log('transaction error', event.target.error)
reject(event.target.error)
}
t.oncomplete = () => {
resolve()
}
records.forEach(record => {
let addReq = nodeStore.add(record)
addReq.onsuccess = (event) => {
console.log('OK!', record.ID, record.Name)
}
addReq.onerror = (event) => {
console.log('Error!', event.target.error, record.ID)
}
})
} catch (e) {
console.log(e)
}
})
}
async getTreeNodes() {
return new Promise((resolve, reject)=>{
let trx = this.db.transaction('nodes', 'readonly')
let nodeStore = trx.objectStore('nodes')
let req = nodeStore.getAll()
req.onsuccess = (event)=>resolve(event.target.result)
req.onerror = (event)=>reject(event.target.error)
})
}
}