Indexdb profile

Indexdb is a browser localised storage, similar to cookies (4K) and localstorage(5m-10m). Indexdb, however, has more storage space and is a non-relational local database.

In the project, the path path drawn by the user needs to be stored so that it can be directly read and rendered on the page in the next visit. Considering the size of the storage space, IndexDB is selected for storage.

Indexdb has the following advantages:

IndexedDB, as the name implies, is a built-in browser database that is non-relational, that is, you do not need to write SQL statements to manipulate the database, and the data is stored in JSON format. IndexedDB is not a NoSQL database. IndexedDB has no concept of tables. In IndexedDB, the object Store is called an object store. 3. Each operation of IndexedDB is a transaction, and each operation to the database is performed within the context of a transaction. 4. Each operation of IndexedDB requires opening the Object Store before performing the specified operation. 5. All operations on IndexedDB are asynchronous.Copy the code

Indexdb encapsulation

Basic database information

    private dbName: string = 'svgData';// Database name
    private version: number = 1;// Database version
    private tableName: string = 'svgPath';// Table name
    private db: IDBDatabase | null = null;
Copy the code

Open the database to create a table

 openDB = () = > {
        return new Promise((resolve,reject) = >{
            const request = window.indexedDB.open(this.dbName, this.version);

            request.onsuccess = (event: any) = > {// The database is successfully opened
                console.log('Database opened successfully')
                this.db = event.target.result
                resolve(1);
            };
    
            request.onupgradeneeded = (event:any) = > {
                console.log('Database created successfully')
                this.db = event.target.result;
                this.create_table(this.db);
            }
    
            request.onerror = (event:any) = > {
                console.log('Database opening error');
                reject(1); }; })}// Create a new table
    create_table  = (idb: any) = > {
        if(! idb.objectStoreNames.contains(this.tableName)) {
            let objectStore;
            objectStore = idb.createObjectStore(this.tableName, { keyPath: 'id' });
            objectStore.createIndex('id'.'id', { unique: true}); }}Copy the code

Read all data (traversal using cursor)

 readAll = () = > {
            return new Promise((resolve,reject) = >{
                if(this.db){
                    let objectStore = this.db.transaction(this.tableName).objectStore(this.tableName);
                    objectStore.openCursor().onsuccess = function (event:any) {
                        var cursor = event.target.result;
                        if (cursor) {
                            UIStore.initPathList(cursor.key,cursor.value);
                            cursor.continue();
                        } else {
                            console.log('No more data! ');
                            resolve(1); }}; }else{ reject(); }})}Copy the code

Increase the data

add  = (newPath:any) = > {
        if(this.db){
            let path = toJS(newPath);
            let request = this.db.transaction([this.tableName], 'readwrite')
            .objectStore(this.tableName)
            .add(path);
            request.onsuccess = function (event:any) {
                console.log('Data write success');
            };
    
            request.onerror = function (event:any) {
                console.log('Data write failure'+event); }}}Copy the code

Update the data

Due to the high frequency of data updates in the project, the IndexDB data updates were buffered

update = _.debounce((newPath:any) = > {
        if(this.db){
            let path = toJS(newPath);
            let request = this.db.transaction([this.tableName], 'readwrite')
            .objectStore(this.tableName)
            .put(path);
            request.onsuccess = function (event:any) {
                console.log('Data updated successfully');
            };

            request.onerror = function (event:any) {
                console.log('Data update failed'); }}},1000, {'maxWait': 10000 })
Copy the code

Delete the data

 remove = (id:number) = > {
        if(this.db){
            let request = this.db.transaction([this.tableName], 'readwrite')
            .objectStore(this.tableName)
            .delete(id);
          request.onsuccess = function (event) {
            console.log('Data deleted successfully'); }; }}Copy the code

Load data during interface initialization

 useEffect(() = > {
    const initPathList = async() = > {try{
        await myIndexDB.openDB();
        await myIndexDB.readAll();
        setNode({ posX: -1.posY: -1.ctrPosX: -1.ctrPosY: -1});// Re-render the page after loading
        console.log('Data loading finished');
      }catch(err){
        console.log('Load failed');
      }
    }
    initPathList();
  }, [])
Copy the code