npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

async-indexed-db

v1.0.3

Published

An asynchronous wrapper for IndexedDB

Downloads

49

Readme

AsyncIndexedDB

A simple, asynchronous wrapper around Javascript IndexedDB. Less than 6kb un-minified. Simplify your IndexedDB code. It's the better way to use IndexedDB.

Features

  • Replace the verbose, event-based IndexedDB API with asynchronous methods.
  • Better error handlling with try, catch instead of callbacks.
  • Provides a simple way to locally store structured data including large files and blobs.
  • Largely reserves the original IndexedDB API. No need to re-learn the API.
  • ObjectStore methods that return an IDBCursor return a simple AsyncIterator instead, making iterating over query results easy. See below for examples.
  • Compatible with all major browsers.

API

class AsyncIndexedDB(db_name: str, schema: Function, version: Int)

Create a IndexedDB with db_name , and the schema, the version number. version is a positive integer.

async open()

Initializes the database by opening and applying its schema if the database is new, or the version has increased.

query(objectStoreName: string, mode = "readwrite", oncomplete: Function, onerror: Function)

Opens a transaction, and creates a ObjectStore proxy. Mode can be either "readwrite" or "readonly". oncomplete and onerror are called when transaction succeeds and when it fails, respectively. The proxy has all the properties and methods of the original IDBObjectStore, but the asynchronous equivalents in place of the event-based methods.

async import(data: Array)

Import data into the IndexedDB. The data needs to be in a form of nested arrays. [[objectStoreName1, [..records], keyPath1], [objectStoreName2, [..records], keyPath2], ...]. keyPath is required for every objectStore without a fixed keyPath defined.

async export(keyRange: Array, count: Int)

Serialize IndexedDB into a nested array form: [[objectStoreName1, [..records], keyPath1], [objectStoreName2, [..records], keyPath2], ...] that can be easily turned into a Map. If keyRange and/or count are defined, they are used together to form a query, and only the resulting records will be exported. If both are undefined, the entire DB will be exported.

Comparison with IndexedDB

These are simple examples, and the difference in code complexity will only increase with proper error handling and data processing.

IndexedDB

// Open database "blog" with version 1.
let DBOpenRequest = window.indexedDB.open("blog", 1);

// error
DBOpenRequest.onerror = function (event) {
    console.log('failed to open db')
};

let db;
DBOpenRequest.onsuccess = function (event) {
    // store the result of opening the database in the db
    db = DBOpenRequest.result;
    success_callback(db);
};

// Data definition if a version upgrade is needed.
DBOpenRequest.onupgradeneeded = function (event) {
    const db = event.target.result;
    db.onerror = function (event) {
        console.log('Error loading database.');
    };
    const objectStore = db.createObjectStore("blog_posts", {keyPath: "id", autoIncrement: true});
    objectStore.createIndex("titleIndex", "title", {unique: false});
    objectStore.createIndex("timeIndex", "time", {unique: false});
};

// put (insert/update) a row into the objectStore (IndexedDB-equivalent of Table)
function success_callback(db) {
    let transaction = db.transaction('blog_posts', 'readwrite');
    let objectStore = transaction.objectStore('blog_posts');
    let request = objectStore.put({
        id: 1,
        title: "sample title",
        time: Date.now(),
        data: "empty body"
    });
    request.onsuccess = function () {
        let request = objectStore.getAll();
        request.onsuccess = function () {
            for (let record of request.result) {
                console.log(record);
            }
        }
    };
    request.onerror = console.log;
    // do the same thing again using an IDBCursor.
    request = objectStore.openCursor();
    request.onsuccess = function (event) {
        const cursor = event.target.result;
        while (cursor) {
            console.log(cursor.value);
            cursor.continue();
        }
    };
}

AsyncIndexedDB

// The data definition schema. The schema is called when the old database version needs to be upgraded.
const schema = async (db) => {
	const objectStore = db.createObjectStore("blog_posts", {keyPath: "id", autoIncrement: true});
	objectStore.createIndex("titleIndex", "title", {unique: false});
	objectStore.createIndex("timeIndex", "time", {unique: false});
	};

// create a database named "blog", and a schema defining function, and a version number.
const db = new AsyncIndexedDB("blog",  schema, 1);

// initialize the database.
await db.open();

// put (insert/update) a record (row) into the objectStore (IndexedDB-equivalent of Table)

const query = db.query('blog_posts')
await query.put({
	id: 1,
	title: 'title',
	time: Date.now(),
	data: 'body'
});

// get all records and iterate over them.
for (let record of await query.getAll()) {
	console.log(record);
}

const cursor = await query.openCursor();

// get a cursor and iterate over the objectStore in another thread.
for await (let {value} of cursor) {
	console.log(value)
}

References

IDBDatabase W3C Recommendation

Using IDBDDatabase MDN