16 PWA - IndexedDB
- IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs.
- IndexedDB is a large scale NoSQL database.
- IndexedDB data is stored as key-value pairs in object stores.
- Supports transactions.
IndexedDB API is not really programmer friendly, use some wrapper library
idb – Jake Archibald’s IndexedDB Promised (idb) is most widely used thin promises based library (written in TS).
Where should data be stored in PWA app?
- URL addressable resources – Cache
- Everything else – IndexedDB
IndexedDB is accessible everywhere – in window, in service worker and in web worker
- Database – cotains object stores, which contain data. Typically one DB per app.
- Object store – similar to tables in classical DB. Data is stores in json (no real types)
- Index – Store used to organize data in another store (reference object store)
- Transaction – same as in regular SQL. Mandatory in IndexedDB for read/write (multithread safety).
- Cursor – Mechanism to iterate over multiple records in DB.
Define DB Schema
Every property is object store
- Value: type stored
- Key: key type
- Indexes: index name and data value type
1 2 3 4 5 6 7 8 9 10 11
idb - open, migrate
Open and upgarde db (migrate data as needed)
1 2 3 4 5 6 7 8 9 10 11 12
idb - save
Save data to db
1 2 3
idb - read/write
Normally read/write operations are wrapped into transaction
1 2 3 4 5
NB! Do not await other thing inside transaction!
- Its common to use single commands inside transactions, so shortcuts are provided by idb library
- get, getKey, getAll, getAllKeys, count, put, add, delete, clear
- getFromIndex, getKeyFromIndex, getAllFromIndex, getAllKeysFromIndex, countFromIndex.
imports in SW
- ES Modules in SW
1 2 3 4
Copy libs to sw source folder, import regulary