Estoy tratando de usar indexedDB por primera vez y quiero crear una clase para ello. Mi código funciona abriendo la base de datos y guardando un objeto, pero cuando intento recuperar el objeto es nulo

var libraries = new storedLibraries();
libraries.openDb();

```
user action
```
libraries.saveLibrary(template);

Clase.

class storedLibraries {
    constructor() {
        this.DB_NAME = 'recording-template';
        this.DB_VERSION = 1;
        this.DB_STORE_NAME = 'library';
        this.db = null;
        this.result = null;
        
        if (!('indexedDB' in window)) {
            console.log('This browser doesn\'t support IndexedDB');
            return;
        }
    }
    
    openDb() {
        var request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
        
        var _self = this;
        request.onsuccess = function (evt) {
            _self.db = this.result;
            _self.getObjectStore();
            console.log(_self.result);
            console.log("openDb DONE");
        };
        request.onerror = function (evt) {
            console.error("openDb:", evt.target.errorCode);
        };

        request.onupgradeneeded = function (evt) {
            console.log("openDb.onupgradeneeded");
            var store = evt.currentTarget.result.createObjectStore(_self.DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
        };
    }
    
    saveLibrary(template) {
        var transaction = this.db.transaction(["library"], "readwrite");
        
        // Do something when all the data is added to the database.
        var _self = this;
        transaction.oncomplete = function(event) {
            console.log("All done!");
        };

        transaction.onerror = function(event) {
            // Don't forget to handle errors!
        };

        var objectStore = transaction.objectStore("library");
        var request = objectStore.add(template);
        request.onsuccess = function(event) {
            // event.target.result
        };
    }
    
    getObjectStore() {
        //console.log(this);
        var transaction = this.db.transaction(["library"], "readwrite");
        var objectStore = transaction.objectStore("library");
        var request = objectStore.getAll();
        
        var _self = this;
        request.onerror = function(event) {
            // Handle errors!
        };
        request.onsuccess = function(event) {
            // Do something with the request.result!
            _self.result = request.result;
            console.log(_self.result);
        };
    }
}

El console.log(_self.result); en getObjectStore () genera el valor correcto pero en openDb () es nulo. He intentado muchas cosas diferentes pero, obviamente, no estoy entendiendo algo.

1
Gary 20 ene. 2021 a las 14:58

1 respuesta

La mejor respuesta

Lo hice funcionar usando promesas.

const libraries = new storedLibraries();
libraries.loadLibraries();

Clase.

class storedLibraries {
    constructor() {
        this.DB_NAME = 'recording-template';
        this.DB_VERSION = 1;
        this.DB_STORE_NAME = 'library';
        this.db = null;
        this.libraries = [];

        if (!('indexedDB' in window)) {
            console.log('This browser doesn\'t support IndexedDB');
            return;
        }
    }
    
    loadLibraries() {
        this.openDb().then((result) => {
            this.getObjectStore().then((result) => {
                for(const res of result) {
                    this.libraries.push(new recordingsTemplate(res));
                }
            });
        }).catch(console.error);
    }

    async openDb() {
        var _self = this;
        const prom = new Promise((resolve, reject) => {
            var request = indexedDB.open(_self.DB_NAME, _self.DB_VERSION);
            
            request.onsuccess = (event) => {
                console.log("openDb:");
                _self.db = request.result;
                resolve(request.result);
            }
            request.onerror = (event) => {
                console.error("openDb:", event.target.errorCode);
                reject(evt);
            }
            
            request.onupgradeneeded = (event) => {
                console.log("openDb.onupgradeneeded");
                _self.db = request.result;
                var store = event.currentTarget.result.createObjectStore(_self.DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
                var transaction = event.target.transaction;
                
                transaction.oncomplete = (event) => {
                    resolve(store);
                }
            }
        });
        return prom;
    }
    
    async getObjectStore() {
        var _self = this;
        const prom = new Promise((resolve, reject) => {
            var transaction = _self.db.transaction(["library"], "readwrite");
            var objectStore = transaction.objectStore("library");
            var request = objectStore.getAll();
            
            request.onerror = (event) => {
                // Handle errors!
                reject(event);
            };
            request.onsuccess = (event) => {
                resolve(request.result);
            };
        });
        return prom;
    }
    
    async saveLibrary(template) {
        var _self = this;
        const prom = new Promise((resolve, reject) => {
            var transaction = _self.db.transaction(["library"], "readwrite");
            
            // Do something when all the data is added to the database.
            transaction.oncomplete = function(event) {
                console.log("All done!");
            };

            transaction.onerror = function(event) {
                // Don't forget to handle errors!
            };

            var objectStore = transaction.objectStore("library");
            var request = objectStore.add(template);
            request.onsuccess = function(event) {
                // event.target.result
            };
        });
        return prom;
    }
}
0
Gary 21 ene. 2021 a las 13:14