indexdDB介紹
IndexedDB是一種 NoSQL 數(shù)據(jù)庫(kù)羡宙,和關(guān)系型數(shù)據(jù)庫(kù)不同的是,IndexedDB是面向?qū)ο蟮模鎯?chǔ)的是Javascript對(duì)象抱完,類(lèi)似mangoDB的存儲(chǔ)方式。
IndexedDB是自帶transaction的刃泡,所有的數(shù)據(jù)庫(kù)操作都會(huì)綁定到特定的事務(wù)上巧娱,并且這些事務(wù)是自動(dòng)提交了,IndexedDB并不支持手動(dòng)提交事務(wù)烘贴。
IndexedDB API大部分都是異步的禁添,在使用異步方法的時(shí)候,API不會(huì)立馬返回要查詢(xún)的數(shù)據(jù)桨踪,而是返回一個(gè)callback老翘。
其異步API的本質(zhì)是向數(shù)據(jù)庫(kù)發(fā)送一個(gè)操作請(qǐng)求,當(dāng)操作完成的時(shí)候锻离,會(huì)收到一個(gè)DOM event铺峭,通過(guò)該event,我們會(huì)知道操作是否成功汽纠,并且獲得操作的結(jié)果卫键。
IndexedDB還有一個(gè)很重要的特點(diǎn)是其同源策略,每個(gè)源都會(huì)關(guān)聯(lián)到不同的數(shù)據(jù)庫(kù)集合虱朵,不同源是不允許訪問(wèn)其他源的數(shù)據(jù)庫(kù)莉炉,從而保證了IndexedDB的安全性钓账,也就是說(shuō)它不允許跨域。
indexdDB使用
1.初始化
let db
let openRequest
//兼容瀏覽器寫(xiě)法
const indexedDB = window.indexedDB || window.webkitIndexedDb || window.mozIndexed || window.msIndexedDB
/**
* 初始化數(shù)據(jù)庫(kù)
* @param {string} dbName 數(shù)據(jù)庫(kù)名
* @param {Array} tableList 數(shù)據(jù)庫(kù)列表
*/
const init = ({ dbName, tableList }) => {
// 向?yàn)g覽器發(fā)送創(chuàng)建數(shù)據(jù)庫(kù)的請(qǐng)求
// 存在就打開(kāi) 不存在就新建 第二個(gè)參數(shù)為db 版本
openRequest = indexedDB.open(dbName)
// 新的數(shù)據(jù)庫(kù)創(chuàng)建 或者數(shù)據(jù)庫(kù)的版本號(hào)被更改會(huì)被觸發(fā)
openRequest.onupgradeneeded = function (e) {
// 表的創(chuàng)建在這個(gè)回調(diào)里執(zhí)行,返回表的實(shí)例
const thisDb = e.target.result
console.log('onupgradeneeded回調(diào)被觸發(fā)' + thisDb)
if (tableList?.length) {
tableList.forEach(table => {
if (!thisDb.objectStoreNames.contains(table.tableName)) {
console.log('數(shù)據(jù)庫(kù)列表不包含這張表絮宁,此時(shí)新建')
// keyPath 主鍵 autoIncrement 是否自增
const objectStore = thisDb.createObjectStore(table.tableName, {
keyPath: table.keyPath,
...table.attr
// autoIncrement: true,
})
if (table.indexName) {
// 創(chuàng)建表的時(shí)候 可以去指定那些字段是可以被索引的字段
objectStore.createIndex(table.indexName, table.indexName, {
unique: table.unique || false
})
}
}
})
} else {
console.error('請(qǐng)傳入數(shù)據(jù)表參數(shù)')
}
}
// 已經(jīng)創(chuàng)建好的數(shù)據(jù)庫(kù)創(chuàng)建成功的時(shí)候
openRequest.onsuccess = function (e) {
db = e.target.result
db.onerror = function (event) {
console.error('DB error: ' + event.target.errorCode)
console.dir(event.target)
}
}
// 打開(kāi)或創(chuàng)建失敗時(shí)調(diào)用
openRequest.onerror = function (e) {
console.error('openRequest.onerror', e)
}
}
點(diǎn)擊按鈕調(diào)用初始化方法梆暮,刷新indexdDb,出現(xiàn)我們創(chuàng)建的數(shù)據(jù)庫(kù)
2.增刪查改
增加一條數(shù)據(jù)
/**
* 新增
* @param {string} tableName 表名
* @param {object} data 數(shù)據(jù)
* @returns {promise}
*/
const add = ({ tableName, data }) => {
return new Promise((suc, fail) => {
const request = db.transaction([tableName], 'readwrite').objectStore(tableName).add(data)
request.onsuccess = function (event) {
suc(event.target)
console.log('數(shù)據(jù)寫(xiě)入成功', event)
}
request.onerror = function (event) {
fail()
console.log('數(shù)據(jù)寫(xiě)入失敗', event)
}
})
}
刪除
/**
* 根據(jù)主鍵刪除對(duì)應(yīng)數(shù)據(jù)
* @param {string} tableName 表名
* @param {string} key 主鍵
* @returns {promise}
*/
const remove = ({ tableName, key }) => {
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.delete(key)
request.onerror = function (event) {
console.error('更新失敗', event)
fail()
}
request.onsuccess = function (event) {
console.log('刪除成功', event)
suc()
}
})
}
查詢(xún)所有數(shù)據(jù)
/**
* 遍歷所有數(shù)據(jù) 使用游標(biāo)來(lái)實(shí)現(xiàn)
* @param {string} tableName 表名
* @returns {promise}
*/
const findAll = tableName => {
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
// 我這里做的是把所有的結(jié)果全部收集起來(lái) 當(dāng)然我們可以做其他事情此處拿到的value是每條數(shù)據(jù)的結(jié)果羞福、還有primaryKey主鍵惕蹄、key、與direction
const result = []
objectStore.openCursor().onsuccess = function (event) {
const cursor = event.target.result
if (cursor) {
result.push({ ...cursor.value })
cursor.continue()
} else {
suc(result)
console.log('findAll成功==>' + result)
}
}
objectStore.openCursor().onerror = function (event) {
console.dir(event)
fail()
}
})
}
查詢(xún)單條數(shù)據(jù)
/**
* 根據(jù)主鍵查詢(xún)對(duì)應(yīng)數(shù)據(jù)
* @param {string} tableName 表名
* @param {string} key 主鍵
* @returns {promise}
*/
const findOneByMainKey = ({ tableName, key }) => {
return new Promise((suc, fail) => {
if (!key) {
fail()
return
}
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.get(key)
request.onerror = function (event) {
console.error('根據(jù)主鍵查詢(xún)對(duì)應(yīng)數(shù)據(jù)', event)
fail()
}
request.onsuccess = function () {
suc(request.result || {})
}
})
}
修改
/**
* 根據(jù)主鍵更新對(duì)應(yīng)數(shù)據(jù)
* @param {object} data 對(duì)應(yīng)的主鍵與值 和 數(shù)據(jù)
* @param {string} tableName 表名
* @returns {promise}
*/
const update = ({ tableName, data }) => {
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.put(data)
request.onerror = function (event) {
console.error('更新失敗', event)
fail()
}
request.onsuccess = function (event) {
console.log('更新成功', event)
suc()
}
})
}
3.其他一些api封裝的方法治专,如關(guān)閉數(shù)據(jù)庫(kù)卖陵,清空表數(shù)據(jù)
源碼index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1, user-scalable=no" />
<title>indexedDB</title>
<style>
.clickBtn {
width: 200px;
height: 46px;
line-height: 46px;
background-color: #2e82ff;
color: #ffffff;
font-size: 18px;
text-align: center;
border-radius: 27px;
position: relative;
cursor: pointer;
margin-right: 20px;
}
.clickBtn::before {
content: '';
position: absolute;
left: 0px;
width: 100%;
height: 100%;
background-image: linear-gradient(to right,
rgba(255, 255, 255, 0) 30%,
rgba(255, 255, 255, 0.2) 50%,
rgba(255, 255, 255, 0) 70%);
background-size: 200%;
animation: wipes 1s infinite;
}
#dataContainer li {
margin-bottom: 20px;
}
#dataContainer li span {
margin-right: 20px;
}
input {
appearance: none;
text-align: center;
height: 36px;
width: 248px;
border-radius: 15px;
border: 0px solid #fff;
padding: 0 8px;
outline: 0;
letter-spacing: 1px;
color: #fff;
font-weight: 600;
background: rgba(45, 45, 45, .10);
border: 1px solid rgba(255, 255, 255, .15);
box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .1) inset;
text-shadow: 0 1px 2px rgba(0, 0, 0, .1);
-o-transition: all .2s;
-moz-transition: all .2s;
-webkit-transition: all .2s;
-ms-transition: all .2s;
color: #2e82ff;
}
@keyframes wipes {
0% {
background-position: 0 0;
}
100% {
background-position: 100% 0;
}
}
</style>
</head>
<body>
<div style="display: flex;width: 100%; margin: 50px auto">
<div class="clickBtn">
<span>初始化數(shù)據(jù)庫(kù)</span>
</div>
<div class="clickBtn">
<span>新增</span>
</div>
<div class="clickBtn">
<span>刪除</span>
</div>
<div class="clickBtn">
<span>修改</span>
</div>
<div class="clickBtn">
<span>查詢(xún)單條數(shù)據(jù)</span>
</div>
<div class="clickBtn">
<span>查詢(xún)所有</span>
</div>
</div>
<div>
<input style="width: 300px;" type="text" placeholder="請(qǐng)輸入需要?jiǎng)h除/更新/查詢(xún)數(shù)據(jù)的主鍵值" id="input" />
<ul id="dataContainer">
</ul>
</div>
<script src="./dbUtils.js"></script>
<script>
let mainData = []
window.onload = () => {
init({
// 數(shù)據(jù)庫(kù)名稱(chēng)
dbName: 'lbcTestDb',
// 數(shù)據(jù)表 數(shù)組 如果要?jiǎng)?chuàng)建多個(gè)表,則寫(xiě)多個(gè)即可
tableList: [
{
// 表名
tableName: 'testTable',
// 主鍵
keyPath: 'name'
// 對(duì)應(yīng)表的其他屬性
// attr:{
// autoIncrement:true, //是否自增
// },
// indexName: 'index',// 索引 不建議使用 因?yàn)槭褂盟饕?當(dāng)前表必須有數(shù)據(jù)否則直接報(bào)錯(cuò)
// unique:false // 對(duì)應(yīng)索引是否唯一
}
]
})
}
// const ulFragment = document.createDocumentFragment()
const getDataToRender = (data) => {
if (!data || !data.length) return
console.log(data)
let liHtml = ''
data.forEach((d, index) => {
console.log(d)
liHtml += `<li><span>第${index + 1}條</span><span>姓名:${d.name}</span><span>工號(hào):${d.employNumber}</span></li>`
});
document.querySelector('#dataContainer').innerHTML = liHtml
}
const getIndexName = (index) => {
return 'lbc' + index
}
const getRandomNumber = () => {
return parseInt(Math.random() * 100000000)
}
const btnDoms = document.querySelectorAll('.clickBtn')
//初始化
btnDoms[0].addEventListener('click', () => {
console.log('初始化')
init({
// 數(shù)據(jù)庫(kù)名稱(chēng)
dbName: 'lbcTestDb',
// 數(shù)據(jù)表 數(shù)組 如果要?jiǎng)?chuàng)建多個(gè)表张峰,則寫(xiě)多個(gè)即可
tableList: [
{
// 表名
tableName: 'testTable',
// 主鍵
keyPath: 'name'
}
]
})
})
//新增
let count = parseInt(Math.random() * 100000)
btnDoms[1].addEventListener('click', () => {
count++
add({
// 加到那個(gè)表里
tableName: 'testTable',
// data是要添加的數(shù)據(jù)
data: {
// 對(duì)應(yīng)的主鍵與值 此處主鍵為name
name: getIndexName(count),
// 數(shù)據(jù)
employNumber: getRandomNumber(),
}
}).then(async () => {
const data = await findAll('testTable')
getDataToRender(data)
})
})
//刪除
btnDoms[2].addEventListener('click', async () => {
// return console.log('11111')
const data = await findAll('testTable')
remove({
tableName: 'testTable',
key: data[4].name,
}).then(async () => {
console.log('刪除第3條')
const data = await findAll('testTable')
getDataToRender(data)
})
})
//修改
btnDoms[3].addEventListener('click', () => {
// return console.log(document.querySelector('#input').value)
let name = document.querySelector('#input').value || 'lbc4'
update({
// 表名
tableName: 'testTable',
// 對(duì)應(yīng)的主鍵與值 和 數(shù)據(jù) 此處主鍵為userId 主鍵值為id
data: {
name,
employNumber: "update" + getRandomNumber()
},
}).then(async () => {
// const data = await findAll('testTable')
// getDataToRender(data)
findOneByMainKey({
// 表名
tableName: 'testTable',
// 主鍵值
key: name,
}).then(async (res) => {
console.log("查詢(xún):" + name, res)
getDataToRender([res])
})
})
})
//查詢(xún)單個(gè)(通過(guò)主鍵)
btnDoms[4].addEventListener('click', () => {
// return console.log('11111')
let name = document.querySelector('#input').value || 'lbc4'
findOneByMainKey({
// 表名
tableName: 'testTable',
// 主鍵值
key: name,
}).then(async (res) => {
console.log("查詢(xún)lbc4", res)
getDataToRender([res])
})
})
//查詢(xún)所有
btnDoms[5].addEventListener('click', () => {
// return console.log('11111')
findAll('testTable'
).then(res => {
console.log("查詢(xún)所有", res)
getDataToRender(res)
})
})
</script>
</body>
</html>
源碼dbUtils.js
// @ts-nocheck
let db
let openRequest
//兼容瀏覽器寫(xiě)法
const indexedDB = window.indexedDB || window.webkitIndexedDb || window.mozIndexed || window.msIndexedDB
/**
* 初始化數(shù)據(jù)庫(kù)
* @param {string} dbName 數(shù)據(jù)庫(kù)名
* @param {Array} tableList 數(shù)據(jù)表
*/
const init = ({ dbName, tableList }) => {
// 向?yàn)g覽器發(fā)送創(chuàng)建數(shù)據(jù)庫(kù)的請(qǐng)求
// 存在就打開(kāi) 不存在就新建 第二個(gè)參數(shù)為db 版本
openRequest = indexedDB.open(dbName)
// 新的數(shù)據(jù)庫(kù)創(chuàng)建 或者數(shù)據(jù)庫(kù)的版本號(hào)被更改會(huì)被觸發(fā)
openRequest.onupgradeneeded = function (e) {
// 表的創(chuàng)建在這個(gè)回調(diào)里執(zhí)行,返回表的實(shí)例
const thisDb = e.target.result
console.log('onupgradeneeded回調(diào)被觸發(fā)' + thisDb)
if (tableList?.length) {
tableList.forEach(table => {
if (!thisDb.objectStoreNames.contains(table.tableName)) {
console.log('數(shù)據(jù)庫(kù)列表不包含這張表泪蔫,此時(shí)新建')
// keyPath 主鍵 autoIncrement 是否自增
const objectStore = thisDb.createObjectStore(table.tableName, {
keyPath: table.keyPath,
...table.attr
// autoIncrement: true,
})
if (table.indexName) {
// 創(chuàng)建表的時(shí)候 可以去指定那些字段是可以被索引的字段
objectStore.createIndex(table.indexName, table.indexName, {
unique: table.unique || false
})
}
}
})
} else {
console.error('請(qǐng)傳入數(shù)據(jù)表參數(shù)')
}
}
// 已經(jīng)創(chuàng)建好的數(shù)據(jù)庫(kù)創(chuàng)建成功的時(shí)候
openRequest.onsuccess = function (e) {
db = e.target.result
db.onerror = function (event) {
console.error('DB error: ' + event.target.errorCode)
console.dir(event.target)
}
}
// 打開(kāi)或創(chuàng)建失敗時(shí)調(diào)用
openRequest.onerror = function (e) {
console.error('openRequest.onerror', e)
}
}
/**
* 新增
* @param {string} tableName 表名
* @param {object} data 數(shù)據(jù)
* @returns {promise}
*/
const add = ({ tableName, data }) => {
return new Promise((suc, fail) => {
const request = db.transaction([tableName], 'readwrite').objectStore(tableName).add(data)
request.onsuccess = function (event) {
suc(event.target)
console.log('數(shù)據(jù)寫(xiě)入成功', event)
}
request.onerror = function (event) {
fail()
console.log('數(shù)據(jù)寫(xiě)入失敗', event)
}
})
}
/**
* 根據(jù)主鍵刪除對(duì)應(yīng)數(shù)據(jù)
* @param {string} tableName 表名
* @param {string} key 主鍵
* @returns {promise}
*/
const remove = ({ tableName, key }) => {
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.delete(key)
request.onerror = function (event) {
console.error('更新失敗', event)
fail()
}
request.onsuccess = function (event) {
console.log('刪除成功', event)
suc()
}
})
}
/**
* 根據(jù)主鍵更新對(duì)應(yīng)數(shù)據(jù)
* @param {object} data 對(duì)應(yīng)的主鍵與值 和 數(shù)據(jù)
* @param {string} tableName 表名
* @returns {promise}
*/
const update = ({ tableName, data }) => {
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.put(data)
request.onerror = function (event) {
console.error('更新失敗', event)
fail()
}
request.onsuccess = function (event) {
console.log('更新成功', event)
suc()
}
})
}
/**
* 遍歷所有數(shù)據(jù) 使用游標(biāo)來(lái)實(shí)現(xiàn)
* @param {string} tableName 表名
* @returns {promise}
*/
const findAll = tableName => {
// return new Promise((suc, fail) => {
// const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
// const result = []
// objectStore.openCursor().onsuccess = function (event) {
// const cursor = event.target.result
// if (cursor) {
// result.push({ ...cursor.value })
// cursor.continue()
// } else {
// suc(result)
// console.log('findAll成功==>' + result)
// }
// }
// objectStore.openCursor().onerror = function (event) {
// console.dir(event)
// fail()
// }
// })
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.getAll()
request.onerror = function (event) {
fail()
console.log('readAll--->讀取表事務(wù)失敗', event)
}
request.onsuccess = function () {
suc(request.result || [])
}
})
}
/**
* 根據(jù)主鍵查詢(xún)對(duì)應(yīng)數(shù)據(jù)
* @param {string} tableName 表名
* @param {string} key 主鍵
* @returns {promise}
*/
const findOneByMainKey = ({ tableName, key }) => {
return new Promise((suc, fail) => {
if (!key) {
fail()
return
}
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.get(key)
request.onerror = function (event) {
console.error('根據(jù)主鍵查詢(xún)對(duì)應(yīng)數(shù)據(jù)', event)
fail()
}
request.onsuccess = function () {
suc(request.result || {})
}
})
}
/**
* 刪除數(shù)據(jù)庫(kù)
* @param {string} DB_NAME 數(shù)據(jù)庫(kù)名稱(chēng)
* @returns
*/
const deleteDB = async DB_NAME => {
return indexedDB.deleteDatabase(DB_NAME)
}
/**
* 關(guān)閉數(shù)據(jù)庫(kù)
* @param {string} DB_NAME 數(shù)據(jù)庫(kù)名稱(chēng)
* @returns
*/
const closeDB = DB_NAME => {
return indexedDB.close(DB_NAME)
}
/**
* 清除表
* @param {string} tableName
* @returns {promise}
*/
const clearTable = tableName => {
return new Promise((suc, fail) => {
const objectStore = db.transaction([tableName], 'readwrite').objectStore(tableName)
const request = objectStore.clear()
request.onerror = function (event) {
console.log('事務(wù)失敗', event)
fail()
}
request.onsuccess = function (event) {
console.log('清除成功', event)
suc()
}
})
}