InDB开发

包的安装和使用

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)
})()

 

posted @ 2021-02-05 17:17  fsl  阅读(297)  评论(0编辑  收藏  举报