SHARE
TWEET

Untitled

a guest Dec 3rd, 2019 80 in 1 day
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. import {openDB}  from "idb";
  3.  
  4. export default function database() {
  5.   let db = null;
  6.   let dbName = null;
  7.   let dbVersion = null;
  8.  
  9.   function isObjStore(db, objectStore){
  10.     return db.objectStoreNames.contains(objectStore);
  11.   }
  12.  
  13.   async function openDb(){
  14.     return db || await openDB(dbName, dbVersion);
  15.   }
  16.  
  17.   async function createDb(props) {
  18.     const {name, version, staticStoreName, dynamicStoreName} = props;
  19.     dbName = name;
  20.     dbVersion = version;
  21.  
  22.     db = await openDB(name, version, {
  23.       upgrade(database, oldVersion, newVersion, transaction) {
  24.         if (!isObjStore(database, staticStoreName)){
  25.           database.createObjectStore(staticStoreName);
  26.         }
  27.  
  28.         if (!isObjStore(database, dynamicStoreName)){
  29.           database.createObjectStore(dynamicStoreName);
  30.         }
  31.       }
  32.     })
  33.   }
  34.  
  35.   async function addRecords(props){
  36.     const {storeName, data} = props;
  37.     getObjectStore(storeName, "readwrite")
  38.       .then((store) => {
  39.         data.forEach(async element => {
  40.           const {key, value} = element;
  41.           await store.put(value, key);
  42.         });
  43.  
  44.       })
  45.       .catch(err => new Error(err));
  46.   }
  47.  
  48.   async function getObjectStore(storeName, mode) {
  49.     const tx = await db.transaction(storeName, mode);
  50.     return tx.objectStore(storeName);
  51.   }
  52.  
  53.   async function deleteObjectStoreData(storeName) {
  54.     getObjectStore(storeName, "readwrite")
  55.       .then(async (store) => {
  56.         await store.clear();
  57.       })
  58.       .catch(err => new Error(err));
  59.   }
  60.  
  61.   return {
  62.     createDb,
  63.     deleteObjectStoreData,
  64.     addRecords,
  65.     openDb
  66.  
  67.   };
  68. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top