前端indexDB封装可支持模糊查询

2019-10-22  本文已影响0人  别老说我好看丶害羞

js

/**
 * 数据库indexDB封装函数
 * create by chenc 2019年10月22日20:33:20
 */
function YYIMIndexDBManager() {

    var db = window.YYIMIndexDB;
    
    // 判断index支持
    function canDBopen() {
        // 创建indexedDB对象,兼容各种浏览器 
        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
        if (!indexedDB) {
            console.log("你的浏览器不支持IndexedDB");
            return false;
        } else {
            return indexedDB;
        }
    }
    // --------------------------------------数据库-----------------------------------------------
    /**
     * 打开数据库
     * @param {*} arg {
     * YYIMIndexDBManager().openIndexDB({
     *      databaseName: 'YYIMDB',
     *      version: 2,
     *      tables: ['person', 'messages']
     *    });
     * }
     */
    function openIndexDB(arg) {

        var indexedDB = canDBopen();
        if(!indexedDB) {
            return;
        }
        var request = indexedDB.open(arg.databaseName || 'YYIMDB', arg.version || 1);

        request.onerror = function (event) {
            window.YYIMIndexDB = null;
            arg.error && arg.error(event);
            console.log('数据库打开报错');
        };


        request.onsuccess = function (event) {
            db = request.result;
            window.YYIMIndexDB = db;
            arg.success && arg.success(db);
            if(arg && arg.tables && arg.tables[0]) {
                arg.tables.forEach(element => {
                    createTable({
                        tableName: element
                    });
                });
            }
            console.log(db, '数据库打开成功');
        };

        request.onupgradeneeded = function (event) {
            db = event.target.result;
            window.YYIMIndexDB = db;
            arg.success && arg.success(db);
            if(arg && arg.tables && arg.tables[0]) {
                arg.tables.forEach(element => {
                    createTable({
                        tableName: element
                    });
                });
            }
            console.log(db, '数据库onupgradeneeded成功');
        };
    }

    // 删除数据库
    function deleteIndexDB(arg) {
        indexedDB.deleteDatabase(arg.databaseName);
    }
    // 关闭数据库
    function closeIndexDB(arg) {
        db.close();
    }

    // --------------------------------------表-----------------------------------------------
    // 创建表
    function createTable(arg) {
        var objectStore, tableName = arg && arg.tableName,
            keyPath = arg && arg.keyPath || 'id';

        if (!db.objectStoreNames.contains(tableName)) {
            objectStore = db.createObjectStore(tableName, {
                keyPath: keyPath
            });
        }
    }

    // 删除表
    function deleteTable(arg) {
        var objectStore, tableName = arg && arg.tableName;

        if (db.objectStoreNames.contains(tableName)) {
            objectStore = db.deleteObjectStore(tableName);
        }
    }
    // 清空表
    function clearTable(arg) {
        if(!arg || !arg.tableName) {
            return;
        }
        var request = db.transaction([arg.tableName], 'readwrite')
            .objectStore(arg.tableName)
            .clear();

        request.onsuccess = function (event) {
            console.log('数据清除成功');
        };

        request.onerror = function (event) {
            console.log('数据清除失败');
        }
    }

    // --------------------------------------数据-----------------------------------------------
    // 插入数据
    function insert(arg) {
        if(!arg || !arg.tableName || !arg.data) {
            return;
        }
        var request = db.transaction([arg.tableName], 'readwrite')
            .objectStore(arg.tableName)
            .add(arg.data);

        request.onsuccess = function (event) {
            console.log('数据写入成功');
            arg.success && arg.success({
                result: request.result,
                type: event.type
            })
        };

        request.onerror = function (event) {
            arg.error && arg.error({
                result: request.result,
                type: event.type
            })
            console.log('数据写入失败');
        }
    }
    //   读取数据
    function read(arg) {

        if(!arg || !arg.tableName) {
            return;
        }
        var transaction = db.transaction([arg.tableName]);
        var objectStore = transaction.objectStore(arg.tableName);
        var request = objectStore.get(arg.keyPath);
        request.onerror = function (event) {
            console.log('事务失败');
        };

        request.onsuccess = function (event) {
            if (request.result) {
                console.log('result: ', request.result);
                arg.success && arg.success({
                    result: request.result
                })
            } else {
                console.log('未获得数据记录');
            }
        };
    }
    /**
     * 遍历数据
     * @param {*} arg {
     * tableName: aaa,
     * match: {
     * key1: 'xxx' xxx模糊匹配key1
     * key2: 'yyy'
     * }
     * }
     */
    function readAll(arg) {
        if(!arg || !arg.tableName) {
            return;
        }
        var objectStore = db.transaction(arg.tableName).objectStore(arg.tableName);
        var result = [];

        objectStore.openCursor().onsuccess = function (event) {
            var cursor = event.target.result;

            if (cursor) {
                if (arg.match) { // 当传入匹配参数时 可以为多个组合匹配 &&
                    var isMatched = true;

                    for (var key in arg.match) {
                        if (arg.match.hasOwnProperty(key)) {
                            var reg = new RegExp(`${arg.match[key]}`, 'gi');

                            if (!cursor.value[key]) {
                                isMatched = false;
                                return;
                            }

                            if (!reg.test(cursor.value[key])) {
                                isMatched = false;
                            }
                        }
                    }

                    if (isMatched) {
                        result.push(cursor.value);
                    }

                } else { // 未传入匹配项 匹配所有的
                    console.log(cursor, 'cursor')
                    result.push(cursor.value);
                }
                cursor.continue();
            } else {
                console.log('没有更多数据了!');
                console.log(result, 'result');
                arg.success && arg.success({
                    result: result
                })
            }
        };
    }
    // 更新数据
    function update(arg) {
        if(!arg || !arg.tableName || !arg.data) {
            return;
        }
        var request = db.transaction([arg.tableName], 'readwrite')
            .objectStore(arg.tableName)
            .put(arg.data);

        request.onsuccess = function (event) {
            arg.success && arg.success({
                result: request.result,
                type: event.type
            })
            console.log('数据更新成功');
        };

        request.onerror = function (event) {
            // // 更新失败执行插入操作
            // insert(arg);
            arg.error && arg.error({
                result: request.result,
                type: event.type
            })
            console.log('数据更新失败');
        }
    }
    // 删除数据
    function remove(arg) {
        if(!arg || !arg.tableName || !arg.keyPath) {
            return;
        }
        var request = db.transaction([arg.tableName], 'readwrite')
            .objectStore(arg.tableName)
            .delete(arg.keyPath);

        request.onsuccess = function (event) {
            arg.success && arg.success({
                result: request.result,
                type: event.type
            })
            console.log('数据删除成功');
        };

        request.onerror = function (event) {
            arg.error && arg.error({
                result: request.result,
                type: event.type
            })
            console.log('数据删除失败');
        }
    }

    return {
        canDBopen: canDBopen,
        openIndexDB: openIndexDB,
        deleteIndexDB: deleteIndexDB,
        closeIndexDB: closeIndexDB,

        createTable: createTable,
        clearTable: clearTable,
        deleteTable: deleteTable,

        insert: insert,
        read: read,
        readAll: readAll,
        update: update,
        remove: remove,
    }
}

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>indexDB Demo</title>
    <script src="./indexDB.js"></script>
</head>
<body>
    <script>
        YYIMIndexDBManager().openIndexDB({
            databaseName: 'YYIMDB',
            version: 2,
            tables: ['person', 'messages']
        });
        setTimeout(() => {
            // 插入1000条数据
            // var i = 0;
            // while(i < 30) {
            //     YYIMIndexDBManager().update({
            //         tableName: 'person',
            //         data: {
            //             id: 'id333_' + i,
            //             name: '张三_' + i,
            //             age: 30,
            //             extra: {
            //                 gender: 'male'
            //             }
            //         }
            //     })
            //     i ++;
            // }

            // // 查询全部数据
            // YYIMIndexDBManager().readAll({
            //     tableName: 'person'
            // });

            // 查询匹配数据
            YYIMIndexDBManager().readAll({
                tableName: 'person',
                match: {
                    name: '张三',
                    age: 30
                },
                success(res) {
                    console.log(res, 'res');
                }
            });

        }, 1000)
    </script>
    <div>
        indexDB
    </div>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读