This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

During the development of Web applications, some data storage requirements will be designed. Common storage methods may include: Saving login cookies; LocalStorage and SessionStorage using the browser’s LocalStorage; WebSQL and IndexedDB involved in persistent storage scheme of client data; Directly stored on the local file system, etc.

Looked into articles: data storage of cookies | August more challenges

This chapter mainly describes the features of IndexedDB and the basic operations such as opening/creating a database, adding, deleting, modifying and querying data, and building an index.


IndexedDB

IndexedDB is a transactional database system similar to an SQL-based relational database management system (RDBMS), but rather than using fixed lists like an RDBMS, it is a javask-based, object-facing database that is closer to NoSQL. It has the following five characteristics.

  • Large storage spaceCompared withLocalStorageandSessionStorageThis may be insufficient depending on the browser10MBThe,IndexedDBGenerally no less250MBThere is no upper limit.
  • Support transactionsThat is, the atomicity required by the transaction operation is satisfied. If one step in the series of operation steps of the transaction fails, the whole transaction will be cancelled.IndexedDBYou roll back to the state you were in before the transaction occurred, without modifying only part of the data.
  • Support for multiple data models.IndexedDBWith an object repository, all types of data can be stored as key/value pairs, and each piece of data is indexed by a unique primary key. The type of storage can be not only objects, strings, but also binary data.
  • The same origin constraint, each web page can only access its own domain name database, cannot cross domain access.
  • asynchronous.IndexedDBWithout blocking the browser’s main thread, it can read and write large amounts of data without slowing down the web page.

How to use

Open or create a database

The first step in using IndexedDB is to open or create a database object.

// Open the database with the specified name. If the database does not exist, create a new database. Const request = window.indexeddb.open ('my_indexeddb','1.0') Request. Onerror = function(event) {console.log(' failed to open database ')} // After opening database successfully, Request. Onsuccess = function(event){// Database object const db = request.result} /** * If the specified version number is larger than the actual version number when the database is opened, the database upgrade event is triggered. * The first thing you do after creating a new database is to create an object repository object. That is to create a table */ request.onneeded = function(event) {const db = event.target.event let objectStore // If (! If (! If (! Ob. ObjectStoreName. The contains (' logs')) {/ / create the log table objects, and specify the primary key objectStore = the createObjectStore (' logs' {keypath: 'id'})}}Copy the code

Add, delete, modify and check data

ObjectStore (); IDBObjectStore (); IDBObjectStore ();

// Create a transaction for log table logs in read/write mode, Const request = db.transaction(['logs'], 'readwrite').objectStore('logs').add({id:1, log: 'hello IndexedDB', time: 1628003429409, user: Request. onSuccess = function(event){console.log(' Data added successfully ')} Request. onError = Function (event){console.log(' failed to add data ')}Copy the code

Similar to adding data, simply replace the add() method with other corresponding methods to achieve delete, modify and query functions, delete using delete() method, modify using put() method, query using get() method. In addition, you can also iterate over the data in the table. The code example is as follows:

// After the object storage object is created, Const objectStore = db.Transaction ('logs').objectStore('logs') objectStore.opencursor ().onSuccess = const objectStore = db.transaction('logs').objectStore('logs') objectStore.opencursor ().onSuccess = Const cursor = event.target.rusult if(cursor){console.log('id:', '); Key.console. log('log:', cursor.value.log) // Move the pointer to the next data item cursor.continue()} else {console.log(' no more data ')}}Copy the code

indexing

Creating an index allows us to search for any field in the table. If there is no index, the default value can only be obtained from the primary key. For example, you can create an index for the user field when creating a log table. The code is as follows:

objectStore.createIndex('user', 'user', { unique: false })
Copy the code

After the index is created, you can use user to search for related data directions. The code example is as follows:

Const request = db.transation(['logs'], 'readonly').objectStore('logs').index('user').get('Jack') Request. onSuccess = function(event) {const result = event.target.result if(result){//... }}Copy the code

conclusion

IndededDB contains a relatively complex API, but you only need to master its object interfaces abstracted from different body weight in the basic operation process. These corpse object interfaces include: Database object IDBDatabase, object warehouse object IDBObjectStore, index object IDBIndex, transaction object IDBTransaction, operation request object IDBRequest, pointer object IDBCursor, primary key collection object IDBKeyRange.