GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

497 lines
15 KiB

2 months ago
  1. # IndexedDB with usability.
  2. This is a tiny (~1.05k brotli'd) library that mostly mirrors the IndexedDB API, but with small improvements that make a big difference to usability.
  3. 1. [Installation](#installation)
  4. 1. [Changes](#changes)
  5. 1. [Browser support](#browser-support)
  6. 1. [API](#api)
  7. 1. [`openDB`](#opendb)
  8. 1. [`deleteDB`](#deletedb)
  9. 1. [`unwrap`](#unwrap)
  10. 1. [`wrap`](#wrap)
  11. 1. [General enhancements](#general-enhancements)
  12. 1. [`IDBDatabase` enhancements](#idbdatabase-enhancements)
  13. 1. [`IDBTransaction` enhancements](#idbtransaction-enhancements)
  14. 1. [`IDBCursor` enhancements](#idbcursor-enhancements)
  15. 1. [Async iterators](#async-iterators)
  16. 1. [Examples](#examples)
  17. 1. [TypeScript](#typescript)
  18. # Installation
  19. ## Using npm
  20. ```sh
  21. npm install idb
  22. ```
  23. Then, assuming you're using a module-compatible system (like webpack, Rollup etc):
  24. ```js
  25. import { openDB, deleteDB, wrap, unwrap } from 'idb';
  26. async function doDatabaseStuff() {
  27. const db = await openDB(…);
  28. }
  29. ```
  30. ## Directly in a browser
  31. ### Using the modules method directly via jsdelivr:
  32. ```html
  33. <script type="module">
  34. import { openDB, deleteDB, wrap, unwrap } from 'https://cdn.jsdelivr.net/npm/idb@7/+esm';
  35. async function doDatabaseStuff() {
  36. const db = await openDB(…);
  37. }
  38. </script>
  39. ```
  40. ### Using external script reference
  41. ```html
  42. <script src="https://cdn.jsdelivr.net/npm/idb@7/build/umd.js"></script>
  43. <script>
  44. async function doDatabaseStuff() {
  45. const db = await idb.openDB(…);
  46. }
  47. </script>
  48. ```
  49. A global, `idb`, will be created, containing all exports of the module version.
  50. # Changes
  51. [See details of (potentially) breaking changes](CHANGELOG.md).
  52. # Browser support
  53. This library targets modern browsers, as in Chrome, Firefox, Safari, and other browsers that use those engines, such as Edge. IE is not supported.
  54. If you want to target much older versions of those browsers, you can transpile the library using something like [Babel](https://babeljs.io/). You can't transpile the library for IE, as it relies on a proper implementation of [JavaScript proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy).
  55. # API
  56. ## `openDB`
  57. This method opens a database, and returns a promise for an enhanced [`IDBDatabase`](https://w3c.github.io/IndexedDB/#database-interface).
  58. ```js
  59. const db = await openDB(name, version, {
  60. upgrade(db, oldVersion, newVersion, transaction) {
  61. // …
  62. },
  63. blocked() {
  64. // …
  65. },
  66. blocking() {
  67. // …
  68. },
  69. terminated() {
  70. // …
  71. },
  72. });
  73. ```
  74. - `name`: Name of the database.
  75. - `version` (optional): Schema version, or `undefined` to open the current version.
  76. - `upgrade` (optional): Called if this version of the database has never been opened before. Use it to specify the schema for the database. This is similar to the [`upgradeneeded` event](https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/upgradeneeded_event) in plain IndexedDB.
  77. - `db`: An enhanced `IDBDatabase`.
  78. - `oldVersion`: Last version of the database opened by the user.
  79. - `newVersion`: Whatever new version you provided.
  80. - `transaction`: An enhanced transaction for this upgrade. This is useful if you need to get data from other stores as part of a migration.
  81. - `blocked` (optional): Called if there are older versions of the database open on the origin, so this version cannot open. This is similar to the [`blocked` event](https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/blocked_event) in plain IndexedDB.
  82. - `blocking` (optional): Called if this connection is blocking a future version of the database from opening. This is similar to the [`versionchange` event](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/versionchange_event) in plain IndexedDB.
  83. - `terminated` (optional): Called if the browser abnormally terminates the connection, but not on regular closures like calling `db.close()`. This is similar to the [`close` event](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/close_event) in plain IndexedDB.
  84. ## `deleteDB`
  85. Deletes a database.
  86. ```js
  87. await deleteDB(name, {
  88. blocked() {
  89. // …
  90. },
  91. });
  92. ```
  93. - `name`: Name of the database.
  94. - `blocked` (optional): Called if the database already exists and there are open connections that don’t close in response to a versionchange event, the request will be blocked until they all close.
  95. ## `unwrap`
  96. Takes an enhanced IndexedDB object and returns the plain unmodified one.
  97. ```js
  98. const unwrapped = unwrap(wrapped);
  99. ```
  100. This is useful if, for some reason, you want to drop back into plain IndexedDB. Promises will also be converted back into `IDBRequest` objects.
  101. ## `wrap`
  102. Takes an IDB object and returns a version enhanced by this library.
  103. ```js
  104. const wrapped = wrap(unwrapped);
  105. ```
  106. This is useful if some third party code gives you an `IDBDatabase` object and you want it to have the features of this library.
  107. This doesn't work with `IDBCursor`, [due to missing primitives](https://github.com/w3c/IndexedDB/issues/255). Also, if you wrap an `IDBTransaction`, `tx.store` and `tx.objectStoreNames` won't work in Edge. To avoid these issues, wrap the `IDBDatabase` object, and use the wrapped object to create a new transaction.
  108. ## General enhancements
  109. Once you've opened the database the API is the same as IndexedDB, except for a few changes to make things easier.
  110. Firstly, any method that usually returns an `IDBRequest` object will now return a promise for the result.
  111. ```js
  112. const store = db.transaction(storeName).objectStore(storeName);
  113. const value = await store.get(key);
  114. ```
  115. ### Promises & throwing
  116. The library turns all `IDBRequest` objects into promises, but it doesn't know in advance which methods may return promises.
  117. As a result, methods such as `store.put` may throw instead of returning a promise.
  118. If you're using async functions, there's no observable difference.
  119. ### Transaction lifetime
  120. TL;DR: **Do not `await` other things between the start and end of your transaction**, otherwise the transaction will close before you're done.
  121. An IDB transaction auto-closes if it doesn't have anything left do once microtasks have been processed. As a result, this works fine:
  122. ```js
  123. const tx = db.transaction('keyval', 'readwrite');
  124. const store = tx.objectStore('keyval');
  125. const val = (await store.get('counter')) || 0;
  126. await store.put(val + 1, 'counter');
  127. await tx.done;
  128. ```
  129. But this doesn't:
  130. ```js
  131. const tx = db.transaction('keyval', 'readwrite');
  132. const store = tx.objectStore('keyval');
  133. const val = (await store.get('counter')) || 0;
  134. // This is where things go wrong:
  135. const newVal = await fetch('/increment?val=' + val);
  136. // And this throws an error:
  137. await store.put(newVal, 'counter');
  138. await tx.done;
  139. ```
  140. In this case, the transaction closes while the browser is fetching, so `store.put` fails.
  141. ## `IDBDatabase` enhancements
  142. ### Shortcuts to get/set from an object store
  143. It's common to create a transaction for a single action, so helper methods are included for this:
  144. ```js
  145. // Get a value from a store:
  146. const value = await db.get(storeName, key);
  147. // Set a value in a store:
  148. await db.put(storeName, value, key);
  149. ```
  150. The shortcuts are: `get`, `getKey`, `getAll`, `getAllKeys`, `count`, `put`, `add`, `delete`, and `clear`. Each method takes a `storeName` argument, the name of the object store, and the rest of the arguments are the same as the equivalent `IDBObjectStore` method.
  151. ### Shortcuts to get from an index
  152. The shortcuts are: `getFromIndex`, `getKeyFromIndex`, `getAllFromIndex`, `getAllKeysFromIndex`, and `countFromIndex`.
  153. ```js
  154. // Get a value from an index:
  155. const value = await db.getFromIndex(storeName, indexName, key);
  156. ```
  157. Each method takes `storeName` and `indexName` arguments, followed by the rest of the arguments from the equivalent `IDBIndex` method.
  158. ## `IDBTransaction` enhancements
  159. ### `tx.store`
  160. If a transaction involves a single store, the `store` property will reference that store.
  161. ```js
  162. const tx = db.transaction('whatever');
  163. const store = tx.store;
  164. ```
  165. If a transaction involves multiple stores, `tx.store` is undefined, you need to use `tx.objectStore(storeName)` to get the stores.
  166. ### `tx.done`
  167. Transactions have a `.done` promise which resolves when the transaction completes successfully, and otherwise rejects with the [transaction error](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/error).
  168. ```js
  169. const tx = db.transaction(storeName, 'readwrite');
  170. await Promise.all([
  171. tx.store.put('bar', 'foo'),
  172. tx.store.put('world', 'hello'),
  173. tx.done,
  174. ]);
  175. ```
  176. If you're writing to the database, `tx.done` is the signal that everything was successfully committed to the database. However, it's still beneficial to await the individual operations, as you'll see the error that caused the transaction to fail.
  177. ## `IDBCursor` enhancements
  178. Cursor advance methods (`advance`, `continue`, `continuePrimaryKey`) return a promise for the cursor, or null if there are no further values to provide.
  179. ```js
  180. let cursor = await db.transaction(storeName).store.openCursor();
  181. while (cursor) {
  182. console.log(cursor.key, cursor.value);
  183. cursor = await cursor.continue();
  184. }
  185. ```
  186. ## Async iterators
  187. Async iterator support isn't included by default (Edge doesn't support them). To include them, import `idb/with-async-ittr` instead of `idb` (this increases the library size to ~1.28k brotli'd):
  188. ```js
  189. import { openDB } from 'idb/with-async-ittr';
  190. ```
  191. Or `https://cdn.jsdelivr.net/npm/idb@7/build/umd-with-async-ittr.js` if you're using the non-module version.
  192. Now you can iterate over stores, indexes, and cursors:
  193. ```js
  194. const tx = db.transaction(storeName);
  195. for await (const cursor of tx.store) {
  196. // …
  197. }
  198. ```
  199. Each yielded object is an `IDBCursor`. You can optionally use the advance methods to skip items (within an async iterator they return void):
  200. ```js
  201. const tx = db.transaction(storeName);
  202. for await (const cursor of tx.store) {
  203. console.log(cursor.value);
  204. // Skip the next item
  205. cursor.advance(2);
  206. }
  207. ```
  208. If you don't manually advance the cursor, `cursor.continue()` is called for you.
  209. Stores and indexes also have an `iterate` method which has the same signature as `openCursor`, but returns an async iterator:
  210. ```js
  211. const index = db.transaction('books').store.index('author');
  212. for await (const cursor of index.iterate('Douglas Adams')) {
  213. console.log(cursor.value);
  214. }
  215. ```
  216. # Examples
  217. ## Keyval store
  218. This is very similar to `localStorage`, but async. If this is _all_ you need, you may be interested in [idb-keyval](https://www.npmjs.com/package/idb-keyval). You can always upgrade to this library later.
  219. ```js
  220. import { openDB } from 'idb';
  221. const dbPromise = openDB('keyval-store', 1, {
  222. upgrade(db) {
  223. db.createObjectStore('keyval');
  224. },
  225. });
  226. export async function get(key) {
  227. return (await dbPromise).get('keyval', key);
  228. };
  229. export async function set(key, val) {
  230. return (await dbPromise).put('keyval', val, key);
  231. };
  232. export async function del(key) {
  233. return (await dbPromise).delete('keyval', key);
  234. };
  235. export async function clear() {
  236. return (await dbPromise).clear('keyval');
  237. };
  238. export async function keys() {
  239. return (await dbPromise).getAllKeys('keyval');
  240. };
  241. ```
  242. ## Article store
  243. ```js
  244. import { openDB } from 'idb/with-async-ittr.js';
  245. async function demo() {
  246. const db = await openDB('Articles', 1, {
  247. upgrade(db) {
  248. // Create a store of objects
  249. const store = db.createObjectStore('articles', {
  250. // The 'id' property of the object will be the key.
  251. keyPath: 'id',
  252. // If it isn't explicitly set, create a value by auto incrementing.
  253. autoIncrement: true,
  254. });
  255. // Create an index on the 'date' property of the objects.
  256. store.createIndex('date', 'date');
  257. },
  258. });
  259. // Add an article:
  260. await db.add('articles', {
  261. title: 'Article 1',
  262. date: new Date('2019-01-01'),
  263. body: '…',
  264. });
  265. // Add multiple articles in one transaction:
  266. {
  267. const tx = db.transaction('articles', 'readwrite');
  268. await Promise.all([
  269. tx.store.add({
  270. title: 'Article 2',
  271. date: new Date('2019-01-01'),
  272. body: '…',
  273. }),
  274. tx.store.add({
  275. title: 'Article 3',
  276. date: new Date('2019-01-02'),
  277. body: '…',
  278. }),
  279. tx.done,
  280. ]);
  281. }
  282. // Get all the articles in date order:
  283. console.log(await db.getAllFromIndex('articles', 'date'));
  284. // Add 'And, happy new year!' to all articles on 2019-01-01:
  285. {
  286. const tx = db.transaction('articles', 'readwrite');
  287. const index = tx.store.index('date');
  288. for await (const cursor of index.iterate(new Date('2019-01-01'))) {
  289. const article = { ...cursor.value };
  290. article.body += ' And, happy new year!';
  291. cursor.update(article);
  292. }
  293. await tx.done;
  294. }
  295. }
  296. ```
  297. # TypeScript
  298. This library is fully typed, and you can improve things by providing types for your database:
  299. ```ts
  300. import { openDB, DBSchema } from 'idb';
  301. interface MyDB extends DBSchema {
  302. 'favourite-number': {
  303. key: string;
  304. value: number;
  305. };
  306. products: {
  307. value: {
  308. name: string;
  309. price: number;
  310. productCode: string;
  311. };
  312. key: string;
  313. indexes: { 'by-price': number };
  314. };
  315. }
  316. async function demo() {
  317. const db = await openDB<MyDB>('my-db', 1, {
  318. upgrade(db) {
  319. db.createObjectStore('favourite-number');
  320. const productStore = db.createObjectStore('products', {
  321. keyPath: 'productCode',
  322. });
  323. productStore.createIndex('by-price', 'price');
  324. },
  325. });
  326. // This works
  327. await db.put('favourite-number', 7, 'Jen');
  328. // This fails at compile time, as the 'favourite-number' store expects a number.
  329. await db.put('favourite-number', 'Twelve', 'Jake');
  330. }
  331. ```
  332. To define types for your database, extend `DBSchema` with an interface where the keys are the names of your object stores.
  333. For each value, provide an object where `value` is the type of values within the store, and `key` is the type of keys within the store.
  334. Optionally, `indexes` can contain a map of index names, to the type of key within that index.
  335. Provide this interface when calling `openDB`, and from then on your database will be strongly typed. This also allows your IDE to autocomplete the names of stores and indexes.
  336. ## Opting out of types
  337. If you call `openDB` without providing types, your database will use basic types. However, sometimes you'll need to interact with stores that aren't in your schema, perhaps during upgrades. In that case you can cast.
  338. Let's say we were renaming the 'favourite-number' store to 'fave-nums':
  339. ```ts
  340. import { openDB, DBSchema, IDBPDatabase } from 'idb';
  341. interface MyDBV1 extends DBSchema {
  342. 'favourite-number': { key: string; value: number };
  343. }
  344. interface MyDBV2 extends DBSchema {
  345. 'fave-num': { key: string; value: number };
  346. }
  347. const db = await openDB<MyDBV2>('my-db', 2, {
  348. async upgrade(db, oldVersion) {
  349. // Cast a reference of the database to the old schema.
  350. const v1Db = db as unknown as IDBPDatabase<MyDBV1>;
  351. if (oldVersion < 1) {
  352. v1Db.createObjectStore('favourite-number');
  353. }
  354. if (oldVersion < 2) {
  355. const store = v1Db.createObjectStore('favourite-number');
  356. store.name = 'fave-num';
  357. }
  358. },
  359. });
  360. ```
  361. You can also cast to a typeless database by omitting the type, eg `db as IDBPDatabase`.
  362. Note: Types like `IDBPDatabase` are used by TypeScript only. The implementation uses proxies under the hood.
  363. # Developing
  364. ```sh
  365. npm run dev
  366. ```
  367. This will also perform type testing.
  368. To test, navigate to `build/test/` in a browser. You'll need to set up a [basic web server](https://www.npmjs.com/package/serve) for this.