npm install z-idb
Now you can require/import z-idb
:
import { get, set } from 'z-idb';
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 'z-idb/dist/esm-compat';
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:
-
z-idb/dist/index.js
EcmaScript module. -
z-idb/dist/index.cjs
CommonJS module.
Legacy builds:
-
z-idb/dist/compat.js
EcmaScript module, transpiled for older browsers. -
z-idb/dist/compat.cjs
CommonJS module, transpiled for older browsers. -
z-idb/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/z-idb@6/dist/umd.js"></script>
<!-- Or in modern browsers: -->
<script type="module">
import { get, set } from 'https://cdn.jsdelivr.net/npm/z-idb@6/+esm';
</script>
import { set } from 'z-idb';
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, Date
s, (IDB also allows arrays of those values, but IE doesn't support it).
All methods return promises:
import { set } from 'z-idb';
set('hello', 'world')
.then(() => console.log('It worked!'))
.catch((err) => console.log('It failed!', err));
import { get } from 'z-idb';
// logs: "world"
get('hello').then((val) => console.log(val));
If there is no 'hello' key, then val
will be undefined
.
Set many keyval pairs at once. This is faster than calling set
multiple times.
import { set, setMany } from 'z-idb';
// 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.
Get many keys at once. This is faster than calling get
multiple times. Resolves with an array of values.
import { get, getMany } from 'z-idb';
// 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),
);
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 'z-idb';
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 'z-idb';
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
.
Delete a particular key from the store.
import { del } from 'z-idb';
del('hello');
Delete many keys at once. This is faster than calling del
multiple times.
import { del, delMany } from 'z-idb';
// 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 all values in the store.
import { clear } from 'z-idb';
clear();
Get all entries in the store. Each entry is an array of [key, value]
.
import { entries } from 'z-idb';
// logs: [[123, 456], ['hello', 'world']]
entries().then((entries) => console.log(entries));
Get all keys in the store.
import { keys } from 'z-idb';
// logs: [123, 'hello']
keys().then((keys) => console.log(keys));
Get all values in the store.
import { values } from 'z-idb';
// logs: [456, 'world']
values().then((values) => console.log(values));
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.
默认基于zly数据库建表
方法 | 参数 | 返回 | 描述 |
getStore | getStore(name: string) | 返回IDBObjectStore | 获取表 |
getIndex | getIndex(name: string, indexName: string) | 返回IDBIndex | 返回索引 |
getValueByIndexField | getValueByIndexField({name = '', indexName = '', field = ''}) | promise | 根据索引和字段获取值 |
getRangeByIndex | getRangeByIndex({name, indexName, idbKeyRange}: any, fn: Function) | promise | 根据索引获取范围 |
getRangeByIndexPage | getRangeByIndexPage({name, indexName, idbKeyRange, pageNum, pageSize}: any, fn: Function) | fn({pageNum, pageSize, list}) | 根据索引分页处理 |
deleteIndex | deleteIndex(name: string, indexName: string) | promise | 删除索引 |
insertRows | insertRows(name: string, collection: Array) | promise | 插入多条 |
insertRow | insertRow(name: string, row: Object) | promise | 插入单条 |
updateRow | updateRow(name: string, row: Object) | promise | 更新单行 |
updateRow | updateRow(name: string, row: Object) | promise | 更新单行 |
updateField | updateField(name: string, key: string, {fields, values}: any) | promise | 更新单行 |
updateRows | updateRows(name: string, collection: Array) | promise | 更新多行 |
deleteRow | deleteRow(name: string, keyPathValue: string) | promise | 删除单条 |
deleteRows | deleteRows(name: string, keyPathValues: Array) | promise | 删除多条 |
getRow | getRow(name: string, key: string) | promise | 获取单条 |
getRows | getRows(name: string, options = []) | promise | 获取单条 |
getKey | getKey(name: string, key: string | number) | promise | 获取主键值 |
getAllKeys | getAllKeys(name: string, options = []) | promise | 获取所有键 |
handleEachCursor | handleEachCursor(name: string, fn: Function, params = []) | fn(event.target.result) | 遍历表 |
getTables | getTables(fn: Function) | fn(res.objectStoreNames) | 遍历表 |
getCounts | getCounts(name: string) | promise | 总条数 |
clearTable | clearTable(name: string) | promise | 删除表 |
deleteDB | deleteDB | promise | 删除库 |