HTML本地存储IndexedDB封装

class IndexedDB{
	    constructor(dbName, storeName, version){
	        this.storeName = storeName;
	        const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB;
	        const request = indexedDB.open(dbName, version);
	
	        request.onsuccess = e => {
	            this.db = e.target.result;
	            console.log('indexDB初始化成功');
	        };
	        request.onupgradeneeded = e => {
	            this.db = e.target.result;
	           if(!this.db.objectStoreNames.contains(storeName)){
	
	           	
	                this.store = this.db.createObjectStore(storeName);
	            }
	            console.log("数据库创建成功,Version:"+version);
	        };
	        request.onerror = e => {console.info('数据库创建失败', e);};
	    }
	    get(key, callback){
	        const transaction = this.db.transaction(this.storeName);
	        const objectStore = transaction.objectStore(this.storeName);
	        const request = objectStore.get(key);
	
	        request.onerror = e => {console.info('获取失败', e);};
	        request.onsuccess = e => {callback(e.target.result);};
	    }
	    set(key, value){
	        let oldValue;
	        this.get(key, function(res){oldValue = res;});
	
	        if(oldValue){
	            console.info('请运用更新方法更新!');
	        }else{
	            const transaction = this.db.transaction(this.storeName, 'readwrite');
	            const objectStore = transaction.objectStore(this.storeName);
	            const request = objectStore.add(value, key);
	
	            request.onerror = e => {console.info('添加失败', e);};
	        }
	    }
	    update(newValue, key){
	        this.get(key,(oldValue)=>{
	        	if(!oldValue){
		            console.info('请用set方法设置值');
		        }else{
		            const transaction = this.db.transaction(this.storeName, 'readwrite');
		            const objectStore = transaction.objectStore(this.storeName);
		            const request = objectStore.put(newValue, key);
		
		            request.onerror = e => {console.info('更新失败', e);};
		        }
	        });
	    }
	    remove(key){
	        const request = this.db.transaction(this.storeName, 'readwrite')
	                .objectStore(this.storeName)
	                .delete(key);
	        request.onerror = e => {console.info('删除失败', e);};
	    }
		delete(name){
	        window.indexedDB.deleteDatabase(name);
	    }
	    close(){
	        this.db.close();
	    }
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值