Created
June 1, 2023 06:40
-
-
Save ekzGuille/b8e023d69167fa900cec0d8898dc600f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const DEFAULT_IONIC_DB = '_ionicstorage'; | |
const DEFAULT_IONIC_TABLE = '_ionickv'; | |
let db; | |
function setupIndexedDb() { | |
return new Promise((resolve, reject) => { | |
if (!indexedDB) { | |
return reject(new Error('indexedDB not suported')); | |
} | |
if (db) { | |
return resolve(db); | |
} | |
const request = indexedDB.open(DEFAULT_IONIC_DB); | |
request.onsuccess = () => { | |
db = request.result; | |
console.log('OPEN'); | |
return resolve(db); | |
}; | |
request.onupgradeneeded = () => { | |
db = request.result; | |
const table = db.createObjectStore(DEFAULT_IONIC_TABLE); | |
console.log('CREATED'); | |
return resolve(db); | |
}; | |
request.onerror = error => { | |
console.log('error indexedDb'); | |
return reject(error); | |
}; | |
return undefined; | |
}); | |
} | |
export function set(key, data) { | |
return setupIndexedDb().then(database => { | |
return new Promise((resolve, reject) => { | |
const transaction = database.transaction( | |
DEFAULT_IONIC_TABLE, | |
'readwrite', | |
); | |
const objectStore = transaction.objectStore(DEFAULT_IONIC_TABLE); | |
const setRequest = objectStore.add(data, key); | |
setRequest.onsuccess = () => { | |
return resolve('data saved'); | |
}; | |
setRequest.onerror = error => { | |
return reject(error); | |
}; | |
}); | |
}); | |
} | |
export function get(key) { | |
return setupIndexedDb().then(database => { | |
return new Promise((resolve, reject) => { | |
const transaction = database.transaction(DEFAULT_IONIC_TABLE, 'readonly'); | |
const objectStore = transaction.objectStore(DEFAULT_IONIC_TABLE); | |
const getRequest = objectStore.get(key); | |
getRequest.onsuccess = data => { | |
return resolve(data?.target?.result); | |
}; | |
getRequest.onerror = error => { | |
return reject(error); | |
}; | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment