Sunday, October 13, 2024
HomeJavaScriptInvestigating IndexedDB Wrapper Libraries - Half Two

Investigating IndexedDB Wrapper Libraries – Half Two


In my put up yesterday I spoke about how I used to be curious about digging into IndexedDB once more, and particularly, how I needed to research some libraries that make utilizing the function a bit simpler. Within the first put up, I described a primary “Contacts” software and demonstrated the code required so as to add persistence with IndexedDB. As we speak I will replace my software to utilize a wrapper library named Dexie.

Dexie is an extremely easy wrapper for IndexedDB and has reactive assist for frameworks together with Vue, React, Svelte, and Angular. Dexie is a free library, however in addition they promote a business sync service known as Dexie Cloud. It makes use of Guarantees which makes utilizing it with async/await even easier. I recommend looking on the in depth docs as I will give attention to simply the elements I must convert my software.

As earlier than, I will skip over discussing DOM stuff and simply give attention to the bits associated to persistence.

Embrace Dexie

Together with Dexie is so simple as including a script ag and pointing to the CDN, https://unpkg.com/dexie/dist/dexie.js. I am utilizing CodePen for my demos so I added it as an exterior script.

Initialize the Database

Keep in mind after I mentioned working with Dexie made IndexedDB easy? Nothing may very well be extra indicative of that than initialization. For comparability’s sake, here is the unique code:

async operate initDb() {
    return new Promise((resolve, reject) => {
        
        let request = indexedDB.open('contacts', 1);

        request.onerror = occasion => {
            alert('Error Occasion, examine console');
            console.error(occasion);
        }
        
        request.onupgradeneeded = occasion => {
            console.log('idb onupgradeneeded firing');

            let db = occasion.goal.consequence;

            let objectStore = db.createObjectStore('contacts', { keyPath: 'id', autoIncrement:true });
            objectStore.createIndex('lastname', 'lastname', { distinctive: false });
        };
        
        request.onsuccess = occasion => {
            resolve(occasion.goal.consequence);
        };
    });
}

Keep in mind, you must open the database after which pay attention for an improve occasion (which can be fired on the primary go to) and do any structural setup there. This entails creating shops and indexes. My demo is not doing any searches so I haven’t got to fret about that.

This is the Dexie model:

async operate initDb() {
    let db = new Dexie('contacts_dexie');
    db.model(1).shops({contacts:'++id'})
    return db;  
}

That is shockingly smaller. To be truthful, this does not truly create the database, it simply “prepares” your net web page. Dexie well delays doing something till you attempt to work with knowledge. But it surely’s essential to notice this if in case you have devtools open and are your databases, you’ll not see something at first.

The second line defines a retailer named contacts. The string worth is the way you outline major keys and indexes. As I haven’t got any indexes only a major key, it is comparatively quick. If I needed to construct an index on the final title property, it will appear like so:

db.model(1).shops({contacts:'++id,lastName'})

Will the simplicity proceed???

Questioning cat

Get All Contacts

Subsequent up is the decision to get all contacts. This is the unique:

async operate getContacts() {
    return new Promise((resolve, reject) => {
        let transaction = db.transaction(['contacts'], 'readonly');
        
        transaction.onerror = occasion => {
            reject(occasion);
        };
        
        let retailer = transaction.objectStore('contacts');
        retailer.getAll().onsuccess = occasion => {
            resolve(occasion.goal.consequence);
        };
    
    });
}

And now the Dexie model:

async operate getContacts() {
    return await db.contacts.toArray();
}

In the event you aren’t impressed but, I do not know what will impress you!

Get One Contact

As soon as once more, the earlier model:

async operate getContact(key) {
    return new Promise((resolve, reject) => {
        let transaction = db.transaction(['contacts'], 'readonly');
        
        transaction.onerror = occasion => {
            reject(occasion);
        };
        
        let retailer = transaction.objectStore('contacts');
        retailer.get(key).onsuccess = occasion => {
            resolve(occasion.goal.consequence);
        };
    
    });
}

And with Dexie:

async operate getContact(key) {
    return await db.contacts.get(key);
}

Saving Contacts

In the event you bear in mind, within the earlier model we used the put API to permit us to have one technique for storing new contacts in addition to updating present ones. This is the unique:

async operate persistContact(contact) {
    return new Promise((resolve, reject) => {
        
        let transaction = db.transaction(['contacts'], 'readwrite');
        transaction.oncomplete = occasion => {
            resolve();
        };
        
        transaction.onerror = occasion => {
            reject(occasion);
        };
        
        let retailer = transaction.objectStore('contacts');
        retailer.put(contact);
        
    });
}

After which Dexie:

async operate persistContact(contact) {
    await db.contacts.put(contact);
}

Deleting Contacts

Lastly, let’s take a look at deleting a contact. This is the unique once more:

async operate removeContact(key) {
    return new Promise((resolve, reject) => {
        let transaction = db.transaction(['contacts'], 'readwrite');

        transaction.oncomplete = occasion => {
            resolve();
        };
        
        transaction.onerror = occasion => {
            reject(occasion);
        };
        
        let retailer = transaction.objectStore('contacts');
        retailer.delete(key);
        
    });
}

And also you get one guess as to what number of strains it’s in Dexie:

async operate removeContact(key) {
    return await db.contacts.delete(key);
}

The Entire Enchilada

Under you may discover the entire software. Actually, I virtually thought-about eradicating my persistence strategies with Dexie being so easy. However I additionally type of assumed that it was good having one technique to deal with DOM occasions and one technique targeted simply on persistence. These capabilities could also be one or two strains every, however having it abstracted like that does allow me to make architectural adjustments later. This is the ultimate software, and once more, forgive the marginally wonky formatting within the embed.

See the Pen IDB1 by Raymond Camden (@cfjedimaster) on CodePen.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments