github.com/pbberlin/go-pwa@v0.0.0-20220328105622-7c26e0ca1ab8/app-bucket/js/db.js (about)

     1  var db = {
     2  
     3      dbInner: null,
     4  
     5      init: async () => {
     6          if (db.dbInner) {
     7              return Promise.resolve(db.dbInner);
     8          }
     9          // the third arg are four funcs inside {}; we cannot rewrite them as arrow funcs nor factor them out :-(
    10          db.dbInner = await idb.openDB('db', 2 , {
    11              upgrade(db, oldVer, newVer, enhTx) {
    12                  // if (db.oldVersion == 0)  db.createObjectStore(...
    13                  if (!db.objectStoreNames.contains('articles')) {
    14                      const store = db.createObjectStore('articles', { keyPath: 'id', autoIncrement: true });
    15                      let idx1 = store.createIndex('price_idx', 'price');
    16                      let idx2 = store.createIndex('date', 'date');
    17                      console.log(`Vs ${oldVer}--${newVer}: db schema: objectStore created `);
    18                  } else {
    19                      console.log(`Vs ${oldVer}--${newVer}: db schema: objectStore exists `);
    20                  }
    21  
    22                  if (!db.objectStoreNames.contains('table2')) {
    23                      const store = db.createObjectStore('table2', {});  // no "in-line keys"
    24                      let idx1 = store.createIndex('idx_name', 'price');
    25                  }
    26  
    27  
    28                  if (oldVer == 1 && newVer == 2) {
    29                      // const tx = db.transaction('articles', 'readwrite'); // cannot use; need to use enhTx
    30                      const store = enhTx.objectStore('articles');
    31                      let idx2 = store.createIndex('date3', 'date3');
    32                      console.log(`Vs ${oldVer}--${newVer}: db schema:  index created `);
    33                  }
    34              },
    35              blocked() { console.error("blocked") },
    36              blocked() { console.error("blocking") },
    37              terminated() { console.error("terminated without db.close()") },
    38          });
    39          console.log("db.objectStoreNames", db.objectStoreNames);
    40          return db.dbInner;
    41      },
    42  
    43  
    44      // const articles = await db.getTableInDB('articles', 'readwrite');
    45      getTableInDB: async (name, mode) => {
    46          const db1 = await db.init();
    47          const tx = db1.transaction(name, mode);
    48          return tx.objectStore(name);
    49      },
    50  
    51      /*
    52      async function getTableInDB(db, name, mode) {
    53          const tx = db.transaction(name, mode);
    54          return tx.objectStore(name);
    55      }
    56  
    57      async function put(db, name, obj) {
    58          const tbl = await getTableInDB(db, name, "readwrite");
    59          return await tbl.put(obj);
    60      }
    61      */
    62  
    63  
    64  }
    65  
    66  
    67  // demo stuff
    68  
    69  
    70  const msg = {
    71      phoneNumber: "phoneNumberField.value",
    72      body:        "bodyField.value",
    73  };
    74  
    75  const art1 = {
    76      title: 'Article 1',
    77      date: new Date('1819-01-01'),
    78      date2: new Date('1839-01-01'),
    79      body: 'content a1',
    80  }
    81  
    82  const art2 = {
    83      title: 'Article 2',
    84      date: new Date('2019-01-01'),
    85      date2: new Date('2039-01-01'),
    86      body: 'content a2',
    87  }
    88  
    89  
    90  
    91  async function doSync() {
    92  
    93      const fcPost = async (msgOrMsgs) => {
    94          const rawResponse = await fetch('https://localhost/save-json', {
    95              method: 'POST',
    96              headers: {
    97                  'Accept': 'application/json',
    98                  'Content-Type': 'application/json'
    99              },
   100              body: JSON.stringify(msgOrMsgs),
   101          });
   102          const rsp = await rawResponse.json();
   103          console.log(`save-json response: `, { rsp });
   104          return rsp;
   105      }
   106  
   107  
   108      // send messages in bulk
   109      try {
   110          const outb = await db.getStore('outbox', 'readonly');
   111          const msgs = await outb.getAll();
   112          const rsps = await fcPost(msgs);
   113          console.log(`save-json bulk response: `, { rsps });
   114      } catch (err) {
   115          console.error(err);
   116      }
   117  
   118  
   119      // send messages each
   120      try {
   121          const outb = await db.getStore('outbox', 'readonly');
   122          const msgs = await outb.getAll();
   123          const rsps = await Promise.all(msgs.map(msg => fcPost(msg)));
   124          console.log(`save-json single response: `, { rsps });
   125      } catch (err) {
   126          console.error(err);
   127      }
   128  
   129  }
   130  
   131  
   132  
   133  /* 
   134      https://github.com/jakearchibald/idb#opendb
   135      https://javascript.info/indexeddb#object-store
   136  
   137  */
   138  
   139  
   140  
   141  
   142  async function dbExample() {
   143  
   144      console.log(`db example start`);
   145  
   146      const dbP = await db.init();
   147      // Add an article:
   148      await dbP.add('articles', art1);
   149      await dbP.add('articles', art2);
   150  
   151  
   152      try {
   153          const tx = dbP.transaction('table2', 'readwrite');
   154          const tbl = tx.objectStore('table2');
   155          const val = (await tbl.get('counter')) || 0;
   156          await tbl.put( val+1, 'counter');
   157          await tx.done;
   158          console.log(`a.) atomic counter val is ${val}`);
   159      } catch (err) {
   160          console.error(err);
   161      }
   162  
   163      // short notation for above - based on idb library wrapper
   164      try {
   165          const val = (await dbP.get('table2', 'counter')) || 0;
   166          await dbP.put('table2',  val+1, 'counter');
   167          console.log(`b.) atomic counter val is ${val}`);
   168      } catch (err) {
   169          console.error(err);
   170      }
   171  
   172      console.log(`db example end`);
   173  
   174  }
   175  
   176  
   177