Giter Club home page Giter Club logo

idb-keyval's Introduction

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.

idb-keyval's People

Contributors

acutmore avatar bennypowers avatar dependabot[bot] avatar diogocorrea avatar forabi avatar hazolsky avatar ianschmitz avatar isidrok avatar jakearchibald avatar jcubic avatar josduj avatar lukasdrgon avatar maug avatar odradek71 avatar outdooricon avatar peterpeterparker avatar philholden avatar remko avatar sidvishnoi avatar styfle avatar tarjei avatar tisvasconcelos avatar y-nk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

idb-keyval's Issues

not working in chrome

Hi Jake, been using this for a while, but it is no longer worker in Chrome:
idbKeyval.set('hello', 'world') .then(() => { console.log('It worked!') }) .catch(err => { console.log('It failed!', err) });
The promise then or catch never get called. Works in ff. Maybe because of idb2 in chrome 58? I hadn't noticed it because I had a fallback.

Configuration for webpack

I'm trying to use this project for React... I've been debugging trying to figure out why stop working from one version to the next one and I found out that is related with webpack.
Not sure if this is the right because is the integration what is failing :/
but this is the error:
idb_keyval__WEBPACK_IMPORTED_MODULE_0__.Store is not a constructor

the code needed to see the error when compiles the code webpack:

const customStore = new Store('db', 'name');

QuotaExceededError

fill your storage device to have no space, then run next code:

var value = 'a'.repeat(50 * 1024 * 1024);
idbKeyval.set('hello', value).finally(x => console.log(x));

QuotaExceededError will cause transaction.onabort, but no transaction.onerror (at least in Chrome 66) as there is no onabort listener, the promise will never be resolved/rejected, seems.

P.S. I was trying to find a good example of IndexedDB usage and found your lib, I don't use it yet.

Add deleteDatabase function

Hi,

It would be really great to add a new function that completely deletes a custom database if it was used. Basically expose indexedDB.deleteDatabase(customDB) and dbInstance.deleteObjectStore(name).

Something along the lines of:

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

const custom = new Store('custom-db-name', 'custom-store-name')
custom.deleteDatabase()

conflict with other lib that use "Store" as default export

vuex also use the same word store which when installing idb we will get an error of reserved import word, so as a solution we could change the class name to something like idb

export class Store {

this way we make sure it doesn't conflict with any other lib of the same nature, this probably means the version will need to be bumped as this will add a breaking change for anyone using the custom store https://github.com/jakearchibald/idb-keyval#custom-stores

Multiple tables

I love idb-keyval - it's perfect for almost all my simple IndexedDB needs, with such a nice API. Thank you!

One thing that I sometimes thing would be nice is if I could make different instances of idbKeyval that are backed by different tables, just so I can separate my data out. Right now I just prefix my keys uniquely and it works out, but that feels a bit messy, and makes dropping all items of a certain category tough (instead of dropping the whole table, I have to iterate the keys and check prefixes). What do you think?

Why doesn't the return value type of `get` include `undefined`?

Is there a reason why get is defined like this?

export function get<Type>(key: IDBValidKey, store = getDefaultStore()): Promise<Type>

ย 
If the key doesn't exist in IDB, the return value is undefined. I personally think:

export function get<Type>(key: IDBValidKey, store = getDefaultStore()): Promise<Type | undefined>

is a better way to define it. This way, you can check if the return value is undefined to see if the get operation succeeded.

Am I missing something?

idbKeyval.clear() doesn't free up space in Chrome

I've been doing some performance testing and am puzzled by the fact that idbKeyval.clear() does not free up temporary storage space in Chrome. In fact, if I repeatedly set and delete a key in IndexedDB using idbKeyval, Chrome DevTools reports a continual growth in storage quota usage.

Here's a simple codepen where you can add ~1kb strings to IndexedDB and then clear them all.
https://codepen.io/pranksinatra/pen/PQweqd

I'm new to IndexedDB and browser storage quotas, so I apologize in advance if I'm missing something obvious. Thanks for pulling together such a concise library--it's been great to work with.

Import { get } from 'idb-keyval' Unexpected Token

I don't get it. I'm not sure how the imports work. But I installed idb-keyval by updating my package.json and I'm told that the brace for the {get} is an unexpected token. I tried npm install idb-keyval but am told no such file or directory exists. I did npm install -g idb-keyval successfully but still doesn't change the brace issue. I don't get how this is supposed to work.

If I just wanted to download the script itself then how would I load it into my serviceworker for use?

serviceworker

Error when trying to build from create react app

Hi!

I'm having a similar issue to #51, however with some small differences and I was wondering if someone could help me.

When trying to run react-scripts build I'm getting the following:

static/js/main.17074a00.js from UglifyJs
SyntaxError: Unexpected token: name (Store) [./~/idb-keyval/dist/idb-keyval-cjs.js:5,0]

I'm using:
"react": "^16.8.6",
"react-scripts": "0.9.x"
My node version is v10.16.0

Let me know if there's any more info you need.
Thank you!

Next major version

The stuff around setting the database & store name has been a bit of a failure. It bloats the library, and renaming stores is a bit of a mess. See the difficulties in #73.

Instead, I think it'd be better to allow developers to provide an object store.

The simple case will remain simple:

// Let the library control the IDB connection:
import { set } from 'idb-keyval';
set('hello', 'world');

If you want to create a database with a custom name and a custom store name:

import { set, createStore } from 'idb-keyval';
const store = createStore('custom-keyval-db', 'custom-keyval-store');
set('hello', 'world', store);

However, if you want to integrate idb-keyval with an existing database, or perform schema migrations on an existing database (like, renaming a store), you'll need to provide a store-getting function:

// TypeScript definition:
function getStore(transactionMode: IDBTransactionMode): IDBObjectStore;

For example:

import { set } from 'idb-keyval';

// Set up an IDB connection manually:
const dbp = new Promise((resolve, reject) => {
  const openreq = indexedDB.open('custom-keyval-db', 1);
  openreq.onerror = () => reject(openreq.error);
  openreq.onsuccess = () => resolve(openreq.result);
  openreq.onupgradeneeded = () => {
    openreq.result.createObjectStore('custom-keyval-store');
  };
});

// A function that gets the target object store:
async function getStore(txMode) {
  return (await dbp).transaction('custom-keyval-store', txMode)
    .objectStore('custom-keyval-store');
}

set('hello', 'world', getStore);

It feels like this keeps the simple cases simple, whilst allowing total control over the underlying database in more custom cases.

The library will become smaller for most users with this change.

More advanced use-cases are better-handled by https://www.npmjs.com/package/idb.

ES module version

It would be nice if this module was available as a standard module.

I'm happy to provide a PR

atomic `update`

Off-topic, but I think this would work as an addition to idb-keyval:

export function update(key: IDBValidKey, updater: (val: any) => any, store = getDefaultStore()): Promise<void> {
  return store._withIDBStore('readwrite', store => {
    const req = store.get(key);
    req.onsuccess = () => {
      store.put(updater(req.result), key);
    };
  });
}

Originally posted by @jakearchibald in WICG/kv-storage#56 (comment)


So I've been using that. It works! Would you consider adding it officially?

set & use a custom store inside webworker

am trying to use the store from a webworker, all working good except using a custom store which keep throwing error db is not a constructor & here is what i currently have

// give error
// const store = require('idb-keyval')
// const db = new store('custom-db-name', 'custom-store-name');

// because using import with webpack gives error
const db = require('idb-keyval')

self.addEventListener('message', async (e) => {
    let {type, key, val} = e.data

    switch (type) {
        case 'get':
            db.get(key)
                .then((res) => self.postMessage(res))
            break

        case 'set':
            db.set(key, val)
                .then(() => self.postMessage(true))
                .catch(() => self.postMessage(false))
            break

        case 'del':
            db.del(key)
                .then(() => self.postMessage(true))
                .catch(() => self.postMessage(false))
            break

        case 'clr':
            db.clear()
                .then(() => self.postMessage(true))
                .catch(() => self.postMessage(false))
            break
    }
})

any help is appreciated ๐ŸŽˆ

how to refresh (updates) the data in the indexedDB ?

I am testing this awesome library with my project.

Just a quick question, how can I auto-update the data in the indexedDB (set maxAge etc) ?

As you know, when the server data get updates, I need to refresh the data in the indexedDB to make the data consistent.

Thank you in advance!

Failed to minify the code from this file

Hey, i am unable to build my project i get the following error:
i am using CRA
Failed to minify the code from this file:
./node_modules/idb-keyval/dist/idb-keyval.mjs:1

Arrow function not supported on older browsers with Parcel

The dist version of idb-keyval uses arrow functions. However, Parcel doesn't transpile code in node_modules, so as a result, idb-keyval doesn't work in a parcel project for browsers such as IE11.

Would it be possible to provide a version in dist that only uses ES5 syntax?

Use "delete" instead of "remove"

Matches ES's Map interface

Maybe add an alias in 1.x and un-document "remove", then kill it in 2.x? Or just jump to 2.0.0 immediately; positive integers are free.

Compatibility with React

I'd like to use this project on my react app, but fails when tries to minify. reason

Any recommendation or plan to fix it?

Thanks I really like the project!!!

Supporting UMD

Hi! Do you have plans to add a distribution with UMD?
I'm trying to use it at ReSpec but I keep getting "ReferenceError: exports is not defined". We actually require AMD but having UMD would be great! I'm happy to send a PR.

cc: @marcoscaceres

older IE versions (11 and 10) show syntax error

I'm not exactly sure what the error is, but debugger points to class Store {} and I suspect that it might be because it's using reserved words as functions such as set/get.

Screen Shot 2019-04-09 at 7 58 39 AM

Any help is well appreciated.

Screen Shot 2019-04-09 at 7 59 00 AM

I'm not intending to make this available to IE11, but IE blocks JS from working and preventing to use other scripts that, in my case, I use to redirect users to a not-supported page.

Any hints would be appreciated.
And thanks for making indexed-db so simple to use!

Looking for feedback on async local storage in the browser

Hi @jakearchibald and watchers,

The Chrome team is contemplating standardizing and shipping an async local storage API with the browser. In fact, it would be layered on top of IndexedDB, in a similar way to idb-keyval. You can see the proposal repository at https://github.com/domenic/async-local-storage.

Given your experience building and supporting this project, we'd love your input on the async local storage proposal. If we were to build things into the browser, what's the ideal API? In particular, we have a number of open API design issues that could use community input.

Thanks!

AbortError: Version change transaction was aborted in upgradeneeded event handler

First of all, thanks for this tiny, reliable library! We've been using it in production at BeFunky, and I've been working on replicating and handling IndexedDB startup issues across browsers (e.g. private modes, QuotaExceeded, etc.).

However, I've been unable to replicate (or understand) this frequently occurring error in Chrome/Opera:

AbortError: Version change transaction was aborted in upgradeneeded event handler.

This error rejects the _dbp Promise in the Store constructor. I've been reaching into the internals a bit so that I can handle startup errors before calling methods on the Store.

My IndexedDB wrapper class looks like this:

this.idbKeyval = require('idb-keyval');

try {
    this.idbKeyvalStore = new this.idbKeyval.Store;
}
catch (error) {
    // Handle an synchronous errors that won't be handled as events by the request.onerror handler
    // For instance, window.indexedDB is undefined in Microsoft Edge during Private Browsing
    return handleError('new idbKeyval.Store failed', error);
}

this.idbKeyvalStore._dbp.then(
    
    // Database successfully opened. Start processing queued requests.
    () => resolve(true),
    
    // Unable to open database
    // The error below is the AbortError mentioned above
    error => handleError('indexedDB.open failed', error)
);

In this case, _dbp.then() rejects with the AbortError.

Just wondered if you'd seen this sort of thing before and could point me in the right direction. If this is outside of the scope of this repo, I totally understand. Thanks!

import not working with webpack/npm

I am using react with webpack but for some reason, the import is not working.

This has been an issue for versions 3.x.

For ex :

import { Store } from 'idb-keyval'

I am getting the error 'Store is not a constructor'.

In the lower versions, import idbkeyval from 'idb-keyval' is working correctly.

Issue using with webpack via require()

const idbKeyval = require('idb-keyval');
...
idbKeyval
      .get(id)
      .then(...)

gives me:

Uncaught TypeError: idbKeyval.get is not a function

Via the console I can see that the browser sees the idbKeyval object like this:

idbKeyval
{default: {...}, __esModule: true}

It looks like I'm hitting this webpack issue, since I've used require() vs. import.

I'm not sure that there's anything for you to do, but FYI this comment aimed at library authors. It might be worth a documentation note for webpack users, since this seems like a common way one might end-up using your lib.

Thanks for writing it, it's really a perfect little wrapper.

Unexpected token: name (Store)

when I try do bundle in preact display it

โœ– ERROR bundle.1c924.js from UglifyJs
Unexpected token: name (Store) [../node_modules/idb-keyval/dist/idb-keyval.mjs:1,0][bundle.1c924.js:5809,6]

localForage actual size

localForage is actually 75kB. Minified 25kB.

Just thought it might improve your case for this library. :)

Host on cdn

Wouldn't hosting this on a CDN make it a lot more easier for this to be used within a service worker?
As idb is the place to be accessed for stored stuff from inside a SW.

error on firefox

DOMError { name: "InvalidStateError", message: "A mutation operation was attempted on a database that did not allow mutations." }

gets triggered by

import { Store, get, set, del, clear, keys } from 'idb-keyval'
const cacheStore = new Store(
   'db-name', // db
    'store-name' // store
)

let now = Date.now() // timestamp

keys(cacheStore).then((keys) => {
    keys.map((key) => {
        get(key, cacheStore).then((item) => {
            if (item.expire < now) {
                return del(item, cacheStore).then(() => {
                    console.log(`${item} removed`)
                }).catch((err) => {
                    console.warn(err)
                })
            }
        })
    })
}).catch((err) => {
    console.error(err)
})

the reason

constructor(dbName = 'keyval-store', storeName = 'keyval') {
    this.storeName = storeName;
    this._dbp = new Promise((resolve, reject) => {
        const openreq = indexedDB.open(dbName, 1); // <<< this line
        openreq.onerror = () => reject(openreq.error);
        openreq.onsuccess = () => resolve(openreq.result);
        // First time setup: create an empty object store
        openreq.onupgradeneeded = () => {
            openreq.result.createObjectStore(storeName);
        };
    });
}

also for some reason i cant find any dbs under storage tab > indexedDB, so not sure if this is an issue with FF, idb, or the lib ๐Ÿ˜’

FF: 59.0.2
OS: osx 10.11.6

DataError: Failed to write blobs.

We are getting this error when writing from some of our users (all Chrome). Resetting their DB fixes it, but that isn't a great solution. Restarting the browser etc doesn't work, it is permanently broken.

The only reference I can find to this error is here: localForage/localForage#788

And indeed we switched to using idb-keyval based on the recommendation in that github issue, but it happens with idb-keyval as well.

I don't think this is an issue with idb-keyval, but I am hoping someone might have some insight into where this comes from.

Add Ethereum name or address to package.json

I would like to see an Ethereum name or address added to the ethereum field of the package.json file. This will allow consumers of the project to know a cannonical address to send funds to. For example, I'm building an application that will allow developers to automatically donate ETH to all of their npm dependencies that have Ethereum addresses in their package.json files: https://sustainus.io

how to have multiple stores under the same db ?

atm i have something like

import { Store, set, get, del, clear } from 'idb-keyval'
const cacheStore = new Store(
    'Media_Manager', // db
    'cacheStore' // store
)
const infoStore = new Store(
    'Media_Manager', // db
    'infoStore' // store
)

but i keep getting the error

Uncaught (in promise) DOMException: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.

and it points to

_withIDBStore(type, callback) {
        return this._dbp.then(db => new Promise((resolve, reject) => {
            const transaction = db.transaction(this.storeName, type); // <<< this line <<<
            transaction.oncomplete = () => resolve();
            transaction.onabort = transaction.onerror = () => reject(transaction.error);
            callback(transaction.objectStore(this.storeName));
        }));
    }

so it that possible or do i've to create new db for each store ?

Potential transaction ordering issue?

Base on the IDB spec, The ordering of the transaction creation determines how the ordering of end result being written

If multiple read/write transactions are attempting to access the same object store (i.e. if they have overlapping scope), the transaction that was created first must be the transaction which gets access to the object store first. Due to the requirements in the previous paragraph, this also means that it is the only transaction which has access to the object store until the transaction is finished.

The specific part of the code in the idb-keyval that I am not sure of is

  _withIDBStore(type: IDBTransactionMode, callback: ((store: IDBObjectStore) => void)): Promise<void> {
    return this._dbp.then(db => new Promise<void>((resolve, reject) => {
  
      const transaction = db.transaction(this.storeName, type);
      ...
  }

Here the transaction is created inside the then() clause of the Promise and there isn't a guarantee ordering of how each Promise is resolved. If that is true, the implication is that when the following code runs

import { set } from 'idb-keyval';
set('foo', 1);
set('foo', 2);

It is not guaranteed that after two set() call resolves, 2 will be persisted.

(That said I could be wrong here... Please correct me if I do since you have a much expert knowledge on JavaScript event loop model works :))

The cool new graphics

Just to be super nit picky, the new graphics in the README look super-cool on npm:

npm

but not-so-super-cool on github:

github

"TypeError: idbKeyval.get is not a function"

here is what i have

const idbKeyval = require('idb-keyval')

getCachedResponse() {
   return idbKeyval.get('bla')
},

// somewhere else
this.getCachedResponse().then((res) => {
    console.log(res)
})

even when using it directly, it still give the same error

idbKeyval.get('bla').then((res) => {
    console.log(res)
})

also is there a chance to add catch() as well instead of checking if the val is undefined ?

discussion: Why idb-keyval is an IIFE instead of being a simple function?

Does it have any special reason why idb-keyval is implemented as an immediately executed function and gets attached to the global scope? Why doesn't it a function which returns an object when being called?

Exposing it as a function would allow a small improvement: allowing to specify the datastore name when initializing the lib.

A way to get everything in the store, similar to idb getAll()

First off, great package! It's been really easy to work with.

While I began configuring everything, I noticed I wanted to get everything in the store. I see idb has a getAll function; is there something similar in this package?

The workaround I thought of using is to iterate over keys and do a get on each key, but I feel like there could be a much more performant way to do this with something like idb's getAll.

Thanks in advance!

Batched set

Would you accept a pull request to extend the API ever so slightly? The idea would be to allow batched setting of data with a setMany:

async function setMany(entries): {
  return store._withIDBStore('readwrite', store => {
    entries.forEach(entry => {
      store.put(entry, entry.f);
    });
  });
}

Testing locally, this allows for much faster batch processing.

Use in Angular 2 app

Hi,

I'm new to JS, Angular, and node.js, do you know how to add idb-keyval and use it in an Angular2 app?
I add <script src="node_modules/idb-keyval/idb-keyval.js"></script> to the base index.html
I add the path to the systemjs.config and to my package.json.

The issue I run into is how do I now import this in a ts module?
I tried these ways:
import { IDBKeyVal, idbKeyVal } from 'idb-keyval';
import 'idb-keyval';
import '../../node_modules/idb-keyval/idb-keyval.js';
It imports it, but it never recognizes idbKeyVal though it is exported.

Any help would be greatly appreciated.

Sincerely,
Michael

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.