Storing Records In IndexedDB

Open an IndexedDB database, write records in one transaction, and read them back by key with a small promise wrapper around events.

JavascriptData Integrity

Code

javascriptsnippet
28 lines
function openDb() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('notes', 1);
    request.onupgradeneeded = () => {
      request.result.createObjectStore('records', { keyPath: 'id' });
    };
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

function run(db, mode, work) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction('records', mode);
    const request = work(tx.objectStore('records'));
    tx.oncomplete = () => resolve(request.result);
    tx.onerror = () => reject(tx.error);
  });
}

const db = await openDb();
await run(db, 'readwrite', (store) =>
  store.put({ id: 'n-1', title: 'first note', tags: ['demo'] }),
);

const saved = await run(db, 'readonly', (store) => store.get('n-1'));
console.log('saved:', saved.title, '| tags:', saved.tags.join(','));
db.close();

How it works

One way to read it: the functions openDb and run, doing all the work.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result is a fresh construction, so callers can keep their originals.

Applying it

The primary signature is function openDb()

Output lines are prefixed (saved:), making each step’s effect easy to spot.

Statements that matter

return new Promise((resolve, reject) => {
  const request = indexedDB.open('notes', 1);
  request.onupgradeneeded = () => {
    request.result.createObjectStore('records', { keyPath: 'id' });
  };
  request.onsuccess = () => resolve(request.result);
  request.onerror = () => reject(request.error);
});
return new Promise((resolve, reject) => {
  const tx = db.transaction('records', mode);
  const request = work(tx.objectStore('records'));
  tx.oncomplete = () => resolve(request.result);
  tx.onerror = () => reject(tx.error);
});
const saved = await run(db, 'readonly', (store) => store.get('n-1'));

Interactive Tools for This Topic

FAQ

Does `openDb` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `openDb`, `run` at load time.