• Stars
    star
    2,446
  • Rank 17,966 (Top 0.4 %)
  • Language
    TypeScript
  • License
    Other
  • Created over 7 years ago
  • Updated 10 months ago

Reviews

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

Repository Details

A super-simple-small promise-based keyval store implemented with IndexedDB

IDB-Keyval

npm

This is a super-simple promise-based keyval store implemented with IndexedDB, originally based on async-storage by Mozilla.

It's small and tree-shakeable. If you only use get/set, the library is ~250 bytes (brotli'd), if you use all methods it's ~534 bytes.

localForage offers similar functionality, but supports older browsers with broken/absent IDB implementations. Because of that, it's orders of magnitude bigger (~7k).

This is only a keyval store. If you need to do more complex things like iteration & indexing, check out IDB on NPM (a little heavier at 1k). The first example in its README is how to create a keyval store.

Installing

Recommended: Via npm + webpack/rollup/parcel/etc

npm install idb-keyval

Now you can require/import idb-keyval:

import { get, set } from 'idb-keyval';

If you're targeting IE10/11, use the compat version, and import a Promise polyfill.

// Import a Promise polyfill
import 'es6-promise/auto';
import { get, set } from 'idb-keyval/dist/esm-compat';

All bundles

A well-behaved bundler should automatically pick the ES module or the CJS module depending on what it supports, but if you need to force it either way:

  • idb-keyval/dist/index.js EcmaScript module.
  • idb-keyval/dist/index.cjs CommonJS module.

Legacy builds:

  • idb-keyval/dist/compat.js EcmaScript module, transpiled for older browsers.
  • idb-keyval/dist/compat.cjs CommonJS module, transpiled for older browsers.
  • idb-keyval/dist/umd.js UMD module, also transpiled for older browsers.

These built versions are also available on jsDelivr, e.g.:

<script src="https://cdn.jsdelivr.net/npm/idb-keyval@6/dist/umd.js"></script>
<!-- Or in modern browsers: -->
<script type="module">
  import { get, set } from 'https://cdn.jsdelivr.net/npm/idb-keyval@6/+esm';
</script>

Usage

set:

import { set } from 'idb-keyval';

set('hello', 'world');

Since this is IDB-backed, you can store anything structured-clonable (numbers, arrays, objects, dates, blobs etc), although old Edge doesn't support null. Keys can be numbers, strings, Dates, (IDB also allows arrays of those values, but IE doesn't support it).

All methods return promises:

import { set } from 'idb-keyval';

set('hello', 'world')
  .then(() => console.log('It worked!'))
  .catch((err) => console.log('It failed!', err));

get:

import { get } from 'idb-keyval';

// logs: "world"
get('hello').then((val) => console.log(val));

If there is no 'hello' key, then val will be undefined.

setMany:

Set many keyval pairs at once. This is faster than calling set multiple times.

import { set, setMany } from 'idb-keyval';

// Instead of:
Promise.all([set(123, 456), set('hello', 'world')])
  .then(() => console.log('It worked!'))
  .catch((err) => console.log('It failed!', err));

// It's faster to do:
setMany([
  [123, 456],
  ['hello', 'world'],
])
  .then(() => console.log('It worked!'))
  .catch((err) => console.log('It failed!', err));

This operation is also atomic – if one of the pairs can't be added, none will be added.

getMany:

Get many keys at once. This is faster than calling get multiple times. Resolves with an array of values.

import { get, getMany } from 'idb-keyval';

// Instead of:
Promise.all([get(123), get('hello')]).then(([firstVal, secondVal]) =>
  console.log(firstVal, secondVal),
);

// It's faster to do:
getMany([123, 'hello']).then(([firstVal, secondVal]) =>
  console.log(firstVal, secondVal),
);

update:

Transforming a value (eg incrementing a number) using get and set is risky, as both get and set are async and non-atomic:

// Don't do this:
import { get, set } from 'idb-keyval';

get('counter').then((val) =>
  set('counter', (val || 0) + 1);
);

get('counter').then((val) =>
  set('counter', (val || 0) + 1);
);

With the above, both get operations will complete first, each returning undefined, then each set operation will be setting 1. You could fix the above by queuing the second get on the first set, but that isn't always feasible across multiple pieces of code. Instead:

// Instead:
import { update } from 'idb-keyval';

update('counter', (val) => (val || 0) + 1);
update('counter', (val) => (val || 0) + 1);

This will queue the updates automatically, so the first update set the counter to 1, and the second update sets it to 2.

del:

Delete a particular key from the store.

import { del } from 'idb-keyval';

del('hello');

delMany:

Delete many keys at once. This is faster than calling del multiple times.

import { del, delMany } from 'idb-keyval';

// Instead of:
Promise.all([del(123), del('hello')])
  .then(() => console.log('It worked!'))
  .catch((err) => console.log('It failed!', err));

// It's faster to do:
delMany([123, 'hello'])
  .then(() => console.log('It worked!'))
  .catch((err) => console.log('It failed!', err));

clear:

Clear all values in the store.

import { clear } from 'idb-keyval';

clear();

entries:

Get all entries in the store. Each entry is an array of [key, value].

import { entries } from 'idb-keyval';

// logs: [[123, 456], ['hello', 'world']]
entries().then((entries) => console.log(entries));

keys:

Get all keys in the store.

import { keys } from 'idb-keyval';

// logs: [123, 'hello']
keys().then((keys) => console.log(keys));

values:

Get all values in the store.

import { values } from 'idb-keyval';

// logs: [456, 'world']
values().then((values) => console.log(values));

Custom stores:

By default, the methods above use an IndexedDB database named keyval-store and an object store named keyval. If you want to use something different, see custom stores.

More Repositories

1

svgomg

Web GUI for SVGO
JavaScript
5,583
star
2

idb

IndexedDB, but with promises
TypeScript
5,582
star
3

sprite-cow

Sprite Cow helps you get the background-position, width and height of sprites within a spritesheet as a nice bit of copyable css.
JavaScript
1,280
star
4

offline-wikipedia

Demo of how something like Wikipedia could be offline-first
HTML
812
star
5

isserviceworkerready

Tracking the status of ServiceWorker in browsers
HTML
563
star
6

simple-serviceworker-tutorial

A really simple ServiceWorker example, designed to be an interactive introduction to ServiceWorker
JavaScript
390
star
7

wittr

Silly demo app for an online course
JavaScript
387
star
8

navigation-transitions

335
star
9

trained-to-thrill

Trains! Yey!
JavaScript
325
star
10

appcache-demo

Python
242
star
11

jakearchibald.com

TypeScript
226
star
12

sass-ie

Writing mobile-first styles without leaving IE<9 behind
Shell
185
star
13

big-web-quiz

JavaScript
110
star
14

wordle-analyzer

TypeScript
95
star
15

tweetdeck-prototype

(mobile|offline)-first Tweetdeck prototype
JavaScript
79
star
16

linear-easing-generator

TypeScript
78
star
17

request-quest

JavaScript
66
star
18

git-convenience

Tools to make git on the terminal a little more pleasureable
Shell
61
star
19

I-rudely-reject-pull-requests-to-this-repo

I will rudely and childishly reject pull requests to the repo
57
star
20

typescript-worker-example

TypeScript
55
star
21

streaming-html

HTML
52
star
22

http2-push-test

JavaScript
51
star
23

safari-14-idb-fix

Working around a Safari IndexedDB bug
JavaScript
42
star
24

cors-playground

TypeScript
41
star
25

sw-routes

Just playing with some ideas
TypeScript
41
star
26

byte-storage

41
star
27

http203-playlist

JavaScript
33
star
28

preso

JavaScript
32
star
29

async-waituntil-polyfill

JavaScript
30
star
30

streaming-include

Throwing around design ideas for a streaming include api
JavaScript
29
star
31

Woosh

Speed testing framework
JavaScript
28
star
32

houdini-paint-flecks

JavaScript
22
star
33

responsive-gallery

An experiment in client-side responsive imagery
JavaScript
18
star
34

LinkTracker

A simple bit of JavaScript to catch clicks to a link that can be logged by any server-side tracking system
JavaScript
18
star
35

sse-fetcher

Server-sent events rewritten on top of fetch
TypeScript
18
star
36

wittr-modern

CSS
17
star
37

easing-worklet

15
star
38

canvas-snow

JavaScript
15
star
39

jank-invaders

JavaScript
15
star
40

mankini

JavaScript
15
star
41

google-album-downloader

Just playing around with some ideas
TypeScript
13
star
42

minesweeper

Just doodling
TypeScript
13
star
43

payments

JavaScript
12
star
44

me

All about me.
12
star
45

ebook-demo

JavaScript
10
star
46

remove-old-service-worker

JavaScript
10
star
47

sw-cache-update-example

JavaScript
10
star
48

scrolly-cliche

JavaScript
10
star
49

font-testing

Testing @font-face support in browsers
PHP
10
star
50

f1-site-optim

Just playing around
TypeScript
9
star
51

supercharged-blog

CSS
9
star
52

range-request-test

This tests how browsers cope with video & range requests.
JavaScript
9
star
53

sass-lessons

Small sass project for a workshop
Shell
9
star
54

frontend-lessons

Teaching someone bits of frontend
8
star
55

flickr-set-fetcher

One-way syncs a Flickr set to disk
JavaScript
7
star
56

streaming-html-spec

JavaScript
7
star
57

image-experiments

Just playing
TypeScript
7
star
58

send-more-bytes-than-length

JavaScript
6
star
59

wikipedia-and-dictionary-title-search

TypeScript
6
star
60

rollup-import-maps-demo

JavaScript
6
star
61

service-worker-benchmark

HTML
6
star
62

configs

Shell
6
star
63

google-photos-downloader-deno

TypeScript
6
star
64

webwords

JavaScript
5
star
65

simple-transition

A small library for controlling transitions with JavaScript
JavaScript
5
star
66

sketch-chain

TypeScript
5
star
67

appcache2serviceworker

Not ready yet
JavaScript
5
star
68

ZoomFix-jQuery-Plugin

Patching jQuery functions that return incorrect values when various browsers are zoomed
JavaScript
5
star
69

http-tinkering

JavaScript
5
star
70

portal-demos

HTML
5
star
71

img-source-sizes-test

TypeScript
4
star
72

jakearchibalddemos

HTML
4
star
73

project-start

Project bootstrapping
JavaScript
4
star
74

f1predictions

F1 predictions thingy. Just me playing with Django really
Python
4
star
75

module-script-demos

JavaScript
3
star
76

accept-encoding-range-test

JavaScript
3
star
77

showrss-downloader

JavaScript
3
star
78

mq-apply

JavaScript
3
star
79

http203-slides

JavaScript
3
star
80

h2-priority-test

JavaScript
3
star
81

streaming-handlebars

An experiment
JavaScript
3
star
82

appcache-credentials

Demo of appcache security issue
JavaScript
3
star
83

money-manager

JavaScript
3
star
84

svgomg-slow

HTML
2
star
85

idb-keyval-build-example

JavaScript
2
star
86

rollup-hash-bug

JavaScript
2
star
87

thing.html

HTML
2
star
88

cache-credentials

JavaScript
2
star
89

idb-minimal-webpack

A minimal webpack config showing the IDB library
JavaScript
2
star
90

rollup-hash-bug-2

JavaScript
2
star
91

pinch-zoomer

JavaScript
2
star
92

jakearchibald

1
star
93

chunked-encoding-request-test

JavaScript
1
star
94

thing.txt

HTML
1
star
95

xbmc-remote

JavaScript
1
star
96

static-stuff

GLSL
1
star
97

multi-dev

Test project for a workshop
1
star
98

rollup-child-build

Just playin
JavaScript
1
star
99

multi-thread-svg-render

1
star
100

history-timeline-generator

TypeScript
1
star