包的安裝和使用
InDB是一個npm包,通過npm進行安裝:
npm i indb
安裝之後,你可以根據你的編程需求選擇不同的使用方式:
// webpack import InDB from 'indb'
// CommonJS const { InDB } = require('indb')
在HTML中直接使用時,你需要把indb/dist/indb.js文件拷貝到你的本地目錄:
<script src="./node_modules/indb/dist/indb.js"></script> <script> const { InDB } = window['indb'] // 注意這裏的使用方法 </script>
使用
參數列表
在進行InDB實例化時,需要傳入參數:
- name: 字符串,數據庫名稱
- version: 正整數,數據庫結構的版本,調整數據庫結構時,需要升級version
- stores: 數組,用以定義當前數據庫中每個store的結構
- name: 字符串,store名稱
- keyPath: 字符串,store keyPath
- indexes: 數組,用以定義store的索引
- name: 字符串,索引名稱
- keyPath: 字符串,索引的keyPath
- unique: boolean,該索引是否是唯一的,不允許同一個store中同索引名存在兩個及以上的索引值
- isKv: boolean,是否開啓key-value模式,爲true時keyPath和indexes無效
const { InDB } = window['indb']
const idb = new InDB({
name: 'mydb',
version: 1,
stores: [
{
name: 'store1',
keyPath: 'id',
indexes: [
{
name: 'indexName',
keyPath: 'age',
}]
},
{
name: 'store2',
isKv: true,
},
],
})
const store1 = idb.use('store1')
const store2 = idb.use('store2')
;(async function() {
// put and get data
await store1.put({ id: 'key1', value: 'value2' })
await store1.put({ id: 'key2', value: '2222222222222'})
await store1.put({ id: 'key3', value: '3333333333333'})
await store1.put({ id: 'key4', value: '4444444444444'})
await store1.put({ id: 'key5', value: '5555555555555'})
await store1.put({ id: 'key6', value: '6666666666666'})
const obj = await store1.get('key1')
// use like key-value storage (as localStorage do)
await store2.setItem('key', 'value')
console.log(obj)
console.log(await store2.get('key'))
getkey=await store1.get('key2')
alert(getkey.id)
alert(getkey.value)
console.dir(await store1.get('key2'))
let objfind = await store1.find('indexName', '555')
let firstRecord = await store1.first()
let lastRecord = await store1.last()
let someRecords = await store1.some(2, 3)//count,start
let count = await store1.count()
let keys = await store1.keys()
console.log(objfind)
})()