background

Existing browser data storage solutions are not suitable for storing large amounts of data: cookies are less than 4KB in size and are sent back to the server on every request; LocalStorage ranges from 2.5MB to 10MB (depending on the browser), and does not provide search function, cannot create a custom index. So, a new solution was needed, and that’s where IndexedDB came from.

In summary, the need for a front-end storage solution with a large storage capacity that supports searching and custom indexing resulted in IndexDB.

IndexDB is a non-relational database. (SQL query not supported)

Why not ls, SS,cookie

localStorage

LocalStorage is a new TECHNOLOGY added to the HTML5 standard, the size is generally 5MB.

It is mainly used to save some users’ configuration on the current host that does not contain sensitive information. Some websites will save user information and even tokens in LS, which is very dangerous.

  • Validity period: it is permanently stored unless it is cleared
  • Communication: Only saved in the client (i.e., the browser), does not participate in the communication with the server
  • Ease of use: The source interface is acceptable and can be repackaged to provide better support for Objects and arrays

sessionStorage

The interface of sessionStorage is similar to that of localStorage. The size of sessionStorage is usually 5MB. It can only save part of the data in the current session, and the data on the refreshed page still exists. However, when the page closes, the data in sessionStorage is cleared.

  • Validity period: Valid only for the current session and will be cleared after you close the page or browser
  • Communication: Only saved in the client (i.e., the browser), does not participate in the communication with the server
  • Ease of use: The source interface is acceptable and can be repackaged to provide better support for Objects and arrays

cookie

Cookie means a small piece of cake. As the name suggests, cookies are very small indeed, limiting their size to about 4KB.

Its main purpose is to store login information, such as “remember your password” when you log into a marketplace. This is usually done by storing a piece of data that identifies the user in a Cookie.

  • Validity period: The validity period is usually generated by the server. You can set the validity period. If cookies are generated on the browser side, they are invalid after the browser is closed by default.
  • Communication: Carried every time in the HTTP header, using cookies to store too much data can cause performance problems.
  • Ease of use: needs to programmer own encapsulation, the source Cookie interface is not friendly

The cookie will be discarded later.

IndexDB characteristics

  • Key-value pair storage (primary key must be unique, otherwise it will be thrown wrong)
  • Asynchronous (do not lock the browser)
  • Support for transactions (if one step fails, cancel the entire transaction, roll back to the previous state, avoid only changing part)
  • The same-origin restrictions
  • Large storage space: at least 250 MB, and no upper limit
  • Support binary storage

The core concept

  • Database: IDBDatabase object. Database has the concept of version. Only one version can be created ata time
  • Object repository: IDBObjectStore objects, similar to tables in a relational database
  • Index: The IDBIndex object can be used to create indexes for different properties in the object repository, and create default indexes for primary keys
  • Transaction: the IDBTransaction object provides an error,abord, and complete callback method that listens for the result of the operation
  • Operation request: IDBRequest object
  • Pointer: IDBCursor object
  • Set of primary keys: an IDBKeyRange object. A primary key is a property that is indexed by default. It can be a property of the current level, a property of the next level, or an increasing integer

Operation process

1. Open the database

var request = window.indexedDB.open(databaseName, version); 
Copy the code

There are three callback methods:

  • Request. onError – Returns an error message
  • Request. onSUCCESS – Returns obj.target.result as the database object
  • Request. onupgradenneeded – Version upgrade, ibid

2. Create a database

Creating a database is the same as opening a database. If the specified database does not exist, it will be created.

Usually, when you create a new database, the first thing you do is create the object repository (that is, create the table), usually to determine whether the table has already been created.

request.onupgradeneeded = function (event) {
  db = event.target.result;
  var objectStore;
  if(! db.objectStoreNames.contains('person')) {
    objectStore = db.createObjectStore('person', { keyPath: 'id' });
    // var objectStore = db.createObjectStore( 
    // 'person',
    // { autoIncrement: true } 
    / /)}}Copy the code

3. Start the transaction

Add, delete, modify and query are implemented through transactions. New transactions need to specify the table name and operation mode (read/write/read only).

Encapsulates the method for creating a transaction:

startTransaction (tableName, mode = 'readwrite') {
  // There are three requirements for creating a transaction
  // A database connection is available.
  // 2, storeName(store name)
  Readonly, readwrite and versionchange
  this.transaction = this.db.transaction(tableName, mode);
  this.transaction.oncomplete = () = > console.log('transaction complete');
  this.transaction.onerror = e= > console.log('error', e);
 }
Copy the code

Transactions are opened when they are created, not when they are requested.

There is a problem to consider, if the same data in a table is operated at the same time, whether there is a problem of data overwriting or loss.

4. Add, delete, modify and check

/ / to add
let request = objectStore.add(data);
/ / check
let request = objectStore.get(id);
/ / traverse
function readAll() {
  var objectStore = db.transaction('person').objectStore('person');
  objectStore.openCursor().onsuccess = function (event) {
    var cursor = event.target.result;
    if (cursor) {
      console.log('Id: ' + cursor.key);
      console.log('Name: ' + cursor.value.name);
      console.log('Age: ' + cursor.value.age);
      console.log('Email: ' + cursor.value.email); cursor.continue();
    } else {
      console.log('No more data! '); }}; }/ / update
let request = objectStore.put(obj);
/ / delete
let request = objectStore.deletet(id);
// Query by index
var store = transaction.objectStore('person');
var index = store.index('name');
var request = index.get('bill');
Copy the code

Application Scenario

The reason why indexDB was connected this time was that it implemented an editor, which needed to localize the content written and the pictures collected. On the one hand, the editor had an unstable client, which would cause the content to be lost if the client stuck. On the other hand, the user can avoid the loss of content without refreshing. Also from the point of view of disconnection and power failure, if you can achieve real-time saving without calling the interface, the content will not be lost after power failure and recovery.

Therefore, the recommended scenario for indexDB, I conclude, is something like this:

  • Requires storage of large amounts of data
  • Frequent reads and writes are required
  • The read and write content is not necessarily the normalized database table structure
  • It is expected that the read and write process will not affect the main process

All in all, indexDB is a database that is easy to use by the browser. With the improvement of front-end function complexity, users need to diversify, front-end indexDB applications are more and more. Desktop application, Progressive Web App (PWA), Chrome extension development, etc. The user will get/manipulate more information at the same time, how to keep this large amount of data, and then our indexDB is online.