• Stars
    star
    205
  • Rank 191,264 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created 11 months ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Practical IndexedDB API

DB64

A Practical IndexedDB API

Disclaimer

Starting from version 0.8.5, before creating a new database, the function db64.create(<database>,[<store>,<store>,...]) will now automatically delete the existing specified database if it does not contain the exact specified stores. If you do not want this behavior, set the third argument to disable-delete e.g. db64.create('db', ['x', 'y'], 'disable-delete')

A more practical alternative to localStorage. db64 supports all major browsers.

db64

  • Promise based API
  • Set and get single or multiple entries
  • Delete single, multiple or all entries
  • No versioning
  • 2.91KB minified | 938 bytes (brotli)

E.g.

import db64 from './db64.js'

try {
  // First create a database with stores
  await db64.create('Games', ['Super Nintendo', 'Gameboy'])

  // Assign a variable for modifying a store
  const snes = db64.use('Games', 'Super Nintendo')

  // Set multiple entries into Super Nintendo
  await snes.setEntries({ adventure: 'Mario World', rpg: 'Zelda', fighting: 'Street Fighter II' })

  // Get multiple entries from Super Nintendo
  await snes.getEntries(['adventure', 'fighting']) // { adventure: 'Mario Wrold', fighting: 'Street Fighter II' }

  // Delete an existing db 
  await db64.delete('Games')
...

Launch an example using npm run d, then navigate to ./examples

Why IndexedDB, why not localStorage?

  • Better performance
  • Asynchronous (localStorage is blocking)
  • Larger storage quota (localStorage is capped at 5MB)
  • Reliable (no type coercion)
  • Uses the structuredClone algorithm

Practical challenges when using IndexedDB

  • It's event driven, without promises
  • It was designed to encourage versioning, which is not necessary for the majority of projects
  • The API is considered low level and can be challenging as a replacement for localStorage
  • Removing databases and stores is not straightforward nor necessary, and usually requires versioning

Just give me the builds

  • git clone [email protected]:julienetie/db64.git
  • cd db64 && npm i
  • npm run prepublishOnly

Install

npm i db64

Import

import db64 from 'db64.js'    // ES (native)
// or
import db64 from 'db64'       // ES
// or
const db64 = require('db64')  // CommonJS

Create a database with stores (string, array, string)

await db64.create('game-consoles', ['n64', 'ps5', 'dreamcast', 'xbox-360'])
// or
await db64.create(..., ..., 'disable-delete')

By default, if the database to create exists but dosn't have the expected stores, it will be deleted before being re-created. This can be disabled by using the 'disable-delete' string.

Check if a database has a store (string, string | array)

const hasN64 = await db64.has('game-consoles', 'n64')
// or
const hasStores = await db64.has('game-consoles', ['n64', 'dreamcast', 'ps5'])

Use a store (string, string)

const n64 = db64.use('game-consoles', 'n64')

Set an entry (IDB type, IDB type) See structured clone algorithm for supported types

await n64.set(5, 'Super Mario 64')

Set multiple entries (object | array)

await n64.setEntries({fps: 'GoldenEye 007', space: 'Star Fox 64', adventure: 'Banjo-Kazooie'})
await n64.setEntries(['Wave Race 64', 'The Legend of Zelda'])

Get an entry (IDB type)

const fps = await n64.get('fps') // GoldenEye 007

Get multiple entries (object | array)

const rareware = await n64.getEntries(['fps', 'adventure', 5]) // {fps: 'GoldenEye 007', adventure: 'Banjo-Kazooie', 0: 'Super Mario 64'}

Delete an entry (IDB type | array)

await n64.delete(1)  // Deletes 'The Legend of Zelda'

Delete multiple entries

await n64.delete(['adventure', 0])  // Deletes 'Banjo-Kazooie' and 'Super Mario 64'

Clear a store (string, string)

await db64.clear('game-consoles', 'n64') // All data in n64 is deleted

Delete a DB (string)

await db64.delete('game-consoles') // game-consoles is deleted

Why db64 opts out of deleting object stores

We are avoiding versioning to keep your life simple. Deleting an existing object stores in IndexedDB triggers a version change. (Whilst compaction may optimise, it doesn't ensure the removal of unwanted data)

Here's the db64 workflow:

  1. Initialise by creating a DB with stores or multiple DBs with stores.

    • By design, you won't be able to add stores to an existing DB later, unless you delete the DB in question
  2. Use a DB.

    • You can make multiple transactions concurrently for multiple DBs, or stores
  3. Set, get and clear data.

  4. Manage the lifecycle of DB deletion and re-creation:

    • When data cannot be retrieved from the user's IndexedDB
    • When there's an error, e.g.:
      • Data corruption
      • Quota exceeded
      • General errors
    • When in the future you decide to add more stores at initialisation
    • When you want to remove stores, especially for data protection

It's important to consider step 4, if not you may leave users stuck because everything will look fine on your computer. Step 4 isn't specific to IndexedDB, it mostly applies to localStorage. It's the same for all persistent storage on all platforms. Your application is at risk of breaking if you decide to change the persistent data structure or add to the structure in the future without preemptively managing common user cases.

// An exhaustive list for handling errors in db64:
switch (e.name) {
    case 'NotFoundError':
    // The operation failed because the requested database object could not be found.
    case 'Db64MissingStore':
    /**
      * An anticipated NotFoundError. Manage both cases together.
      *
      * You will likely need to re-create your database here with necessary stores 
      * and re-populate with existing data if necessary. 
      */ 
        break
    case 'AbortError':
        // A request was aborted.
        break
    case 'SecurityError':
        // Handle security error 
        break
    case 'DataError':
        // Data provided to an operation does not meet requirements.
        break
    case 'TransactionInactiveError':
        // A request was placed against a transaction which is currently not active or has been finished.
        break
    case 'InvalidStateError':
        // The object is in an invalid state.
        break
    case 'ConstraintError':
        // A mutation operation in the transaction failed because a constraint was not satisfied.
        break
    case 'SyntaxError':
        // The keyPath argument contains an invalid key path.
        break
    case 'QuotaExceededError':
        // The operation failed because there was not enough remaining storage space, or the storage quota was reached and the user declined to provide more space to the database.
        break
    case 'ReadOnlyError':
        // The mutating operation was attempted in a read-only transaction.
        break
    case 'UnknownError':
        // The operation failed for reasons unrelated to the database itself and not covered by any other errors.
        break
}

If you do require versioning consider using idb. If you're not building a progressive web app (PWA) you probably don't need versioning.

Contributors

Don't hesitate just contribute, it's a tiny library we will figure it out.

If you want to edit ./README.md edit ./src/_readme.md which will update ./README.md when node create-distribution.js is called. This is to keep the minified size accurate.


MIT Β© Julien Etienne 2024

More Repositories

1

request-frame

The most complete requestAnimationFrame | cancelAnimationFrame polyfill
JavaScript
67
star
2

mimetic

Scalable Fonts
JavaScript
31
star
3

resizilla

window resize events with debounce, mobile orientation change and destroy.
JavaScript
13
star
4

vscode-template-literals

The VS Code Syntax Highlighter for using HTML and SVG in Template Literals
JavaScript
6
star
5

hypertext

Create HTML in JavaScript via virtual-dom VTrees or directly to the DOM: virtual-hyperscript alternative
JavaScript
5
star
6

create-interface

Create Custom Elements for Declarative and Functional Programming
JavaScript
5
star
7

detect-browser

Modern browser detection
JavaScript
4
star
8

xsskillah

A Fast Minimal HTML Sanitizer for the Web
JavaScript
3
star
9

localdb

A simple indexedb wrapper
JavaScript
3
star
10

web-streamer

HTML
2
star
11

typecase

A type checker for dynamically typed JavaScript
JavaScript
2
star
12

soucouyant-old

Functional Persistent State for Humans
JavaScript
2
star
13

lambdascript

The Vanilla JavaScript Standard for Modern Best Practices
JavaScript
2
star
14

aventador

High Performance Element Manipulation
JavaScript
1
star
15

jekyllhyde

A boilerplate for compiling seperate modern browser and IE11-like scripts
JavaScript
1
star
16

bonita

Web SDK
JavaScript
1
star
17

test-apng

JavaScript
1
star
18

observe

A helper function to mutate the DOM .then perform an action after
JavaScript
1
star
19

img

1
star
20

webpack2-boilerplate

A simple Babel, ES6, PostCSS, Autoprefix, Sass, Images boilerplate for web projects.
JavaScript
1
star
21

wavefront_prototype

JavaScript DOM Engine
JavaScript
1
star
22

go-elasticsearch

Go
1
star
23

mocha-chai-es6-jsdom-boilerplate

Mocha Chai ES6 JSDOM Boilerplate
JavaScript
1
star
24

TAaSoJS-1995

The Art and Science of JavaScript - Selective Internal and External Resources
1
star
25

fibonacci-go

Different ways to calculate the fibonacci sequence in golang.
Go
1
star
26

WAVE-Architecture

1
star
27

basic-colly-scraper

A simple colly cli for scraping on the fly
Go
1
star
28

transition-end

Transition End helper using promises
JavaScript
1
star
29

make-web-icons

Generate modern web icons (WIP)
JavaScript
1
star
30

status

Basic state management
JavaScript
1
star
31

wavefront

The Anti Framework
JavaScript
1
star