使用indexDB对接口请求进行简单的缓存数据处理

export function _getAction (url: string, param?: any, header?: any){
    return new Promise((resovle: any, error: any)=>{
        indexDBMap.getDataByKey(JSON.stringify({url, param, header})).then((res: any)=>{
            resovle(res);
        }).catch(()=>{
            getAction(url, param, header).then((res: any)=>{
                indexDBMap.addData(JSON.stringify({url, param, header}), JSON.stringify(res));
                resovle(res);
            });
        })
    });
    
    // return getAction(url, param, header).then((res: any)=>{
    //     indexDBMap.addData(JSON.stringify({url, param}), JSON.stringify(res));
    //     return res;
    // });
} 

export function _postAction (url: string, param?: any, header?: any){
    return new Promise((resovle: any, error: any)=>{
        indexDBMap.getDataByKey(JSON.stringify({url, param, header})).then((res: any)=>{
            resovle(res);
        }).catch(()=>{
            postAction(url, param, header).then((res: any)=>{
                indexDBMap.addData(JSON.stringify({url, param, header}), JSON.stringify(res));
                resovle(res);
            });
        })
    });
}

// 开启缓存工具
class IndexDBMap {

    public databaseName = "arcgisMapIndexDB-chenxian";

    public storeName = "cacheData";

    public version = 1;

    public indexDB: any;

    constructor (){

        this.databaseName = "arcgisMapIndexDB-chenxian";
        this.version = 1;
        this.getIndexDB();

    }

    public getIndexDB (){
        var request = window.indexedDB.open(this.databaseName, this.version);
        request.onerror = function(event) {
            // console.log('缓存系统打开报错');
        }
        var db;
        request.onsuccess = (event)=> {
            db = request.result;
            // console.log('缓存系统打开成功');
            this.indexDB = db;
        }
        request.onupgradeneeded = (event: any)=> {
            db = event.target.result;
            // console.log("缓存系统更新成功");
            this.indexDB = db;

            // 数据库创建或升级的时候会触发
            let objectStore
            if (!db.objectStoreNames.contains(this.storeName)) {
                objectStore = db.createObjectStore(this.storeName, { keyPath: 'id' }) // 创建表
            // objectStore.createIndex('name', 'name', { unique: true }) // 创建索引 可以让你搜索任意字段
            }
        }
    }

    // 添加数据
    public addData (id: string, data: string, db: any = this.indexDB, storeName: string = this.storeName) {
        let request = db.transaction([storeName], 'readwrite') // 事务对象 指定表格名称和操作模式("只读"或"读写")
        .objectStore(storeName) // 仓库对象
        .add({ id, data })
    
        request.onsuccess = function() {
            // console.log('数据缓存成功', id);
        }
    
        request.onerror = function(event: any) {
            console.log('数据缓存失败', event.target.error)
            // throw new Error(event.target.error)
        }
    }

    getDataByKey(key: string, db: any = this.indexDB, storeName: string = this.storeName) {
        return new Promise((resovle: any, error: any)=>{
            let transaction = db.transaction([storeName]) // 事务
            let objectStore = transaction.objectStore(storeName) // 仓库对象
            let request = objectStore.get(key)
    
            request.onerror = function() {
                // console.log('查询失败')
                error();
            }
    
            request.onsuccess = function() {
                // console.log('缓存查询结果: ', request.result)
                if ( request.result )  {
                    resovle(JSON.parse(request.result.data));
                } else {
                    error();
                }
            }
        })
    }
}

const indexDBMap = window.indexDBMap = new IndexDBMap()

 

posted @ 2023-02-15 11:11  blurs  阅读(97)  评论(0编辑  收藏  举报