javascript 对索引资料的API简单的包装

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 对索引资料的API简单的包装相关的知识,希望对你有一定的参考价值。

var localDatabase = {};
localDatabase.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
localDatabase.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;

var debugMode = false;
const OPEN_DB_SUCCESS = "打开数据库成功!",
    OPEN_DB_FAILURE = "打开数据库失败!",
    NOT_OPEN_DB = "未打开数据库!",
    INSERT_RECORD_SUCCESS = "插入数据成功!",
    INSERT_RECORD_FAILURE = "插入数据失败!",
    UPDATE_RECORD_SUCCESS = "更新数据成功!",
    UPDATE_RECORD_FAILURE = "更新数据失败!",
    DELETE_RECORD_SUCCESS = "删除数据成功!",
    DELETE_RECORD_FAILURE = "删除数据失败!",
    CLEAR_TB_SUCCESS = "清空数据表成功!",
    CLEAR_TB_FAILURE = "清空数据表失败!",
    CREATE_TB_SUCCESS = "创建表成功!",
    CRATE_TB_FAILURE = "创建表失败!";

var DB = "db_user",VERSION = 2.0;
/*打开数据库*/
function openDB(dbName, version, objStore, columnArr) {
    var db = localDatabase.db;
    try {
        if (db) db.close();
        version = version || 1;
        var openRequest = localDatabase.indexedDB.open(dbName, version);
        openRequest.onerror = errHandler;

        openRequest.onsuccess = function() {
            messageTips(OPEN_DB_SUCCESS);

            localDatabase.db = openRequest.result;
        };
        openRequest.onupgradeneeded = function(e) {
            var db = e.currentTarget.result;
            if (!db.objectStoreNames.contains(objStore)) {
                var store = db.createObjectStore(objStore, {
                    keyPath: "id"
                });
                for (var i = 0, len = columnArr.length; i < len; i++) {
                    store.createIndex(columnArr[i], columnArr[i], {
                        unique: false
                    });
                }

                messageTips(CREATE_TB_SUCCESS);
            }
        };
        openRequest.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}
/*添加数据*/
function insertDatas(objStore, datas) {
    try {

        var transaction = localDatabase.db.transaction(objStore, "readwrite");
        var store = transaction.objectStore(objStore);

        if (localDatabase && localDatabase.db) {
            var requestArr = [];

            function requestSuccess(e) {
                messageTips(INSERT_RECORD_SUCCESS);
            }
            for (var i = 0; i < datas.length; i++) {
                var request = store.add(datas[i]);

                request.cnt = i;

                requestArr.push(request);

                requestArr[i].onsuccess = requestSuccess;

                requestArr[i].onerror = errHandler;
            }
        }
    } catch (e) {
        messageTips(e.message);
    }
}

/*删除数据库*/
function deleteDB(dbName) {
    localDatabase.indexedDB.deleteDatabase(dbName);
    var tips = "数据库:" + dbName + ",成功删除!";
    console.log(tips);
    $("#control").text($("#control").text() + "\n" + tips);
}

/*关闭数据库*/
function closeDB(dbName) {
    var db = localDatabase.db;
    var request = db.close();
    request.onsuccess = function() {
        messageTips(CLOSE_DB_SUCCESS);
    };
    request.onerror = errHandler;
}
/*通过主键,更新数据*/
function updateDataByKey(objStore, key, value) {

    var db = localDatabase.db;
    try {
        var transaction = db.transaction(objStore, 'readwrite'),
            store = transaction.objectStore(objStore),
            request = store.get(key);
        request.onsuccess = function(e) {
            var record = e.target.result;
            //只更新存在且不为空的数据
            for (var valKey in value) {
                if (value[valKey] && record[valKey]) {
                    record[valKey] = value[valKey];
                }
            }
            store.put(record);
            messageTips(UPDATE_RECORD_SUCCESS);
        };
        request.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}
/*通过字段更新键值*/
function updateDataByColValue(objStore, colName, colValue, value) {

    var db = localDatabase.db;
    try {
        var transaction = db.transaction(objStore, "readwrite"),
            store = transaction.objectStore(objStore),
            index = store.index(colName),
            range = localDatabase.IDBKeyRange.only(colValue),
            request = index.openCursor(range);

        request.onsuccess = function(e) {
            var cursor = e.target.result;
            var record;
            if (cursor) {
                record = cursor.value;
            }

            //只更新存在且不为空的数据
            for (var valKey in value) {
                if (value[valKey] && record[valKey]) {
                    record[valKey] = value[valKey];
                }
            }
            store.put(record);
            messageTips(UPDATE_RECORD_SUCCESS);
        };
        request.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}
/**
 * [用作数据库操作消息提示]
 * @return {[type]} [description]
 */
function messageTips(message) {
    if(debugMode)
    console.log(message);
}
/*根据键值删除记录*/
function deleteDataByKeys(storeName, keys) {
    var db = localDatabase.db;
    try {
        var transaction = db.transaction(storeName, 'readwrite');
        var store = transaction.objectStore(storeName);
        var request;
        for (var i = 0; i < keys.length; i++) {
            request = store.delete(keys[i]);
        }
        request.onsuccess = function() {
            messageTips(DELETE_RECORD_SUCCESS);
        };
        request.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}
/*清空数据存储*/
function clearObjectStore(storeName) {
    var db = localDatabase.db;

    var transaction = db.transaction(storeName, 'readwrite');
    var store = transaction.objectStore(storeName);
    var request = store.clear();

    request.onsuccess = function() {
        messageTips(CLEAR_TB_SUCCESS);
    };
    request.onerror = errHandler;
}
/*错误处理*/
function errHandler() {
    messageTips(arguments[0].message);
}
/*查询全部记录*/
//recordArr记录查询结果,reqFlag请求完成旗标
var recordArr = [];

function queryAllRecords(objStore) {
    recordArr = [];
    var db = localDatabase.db;
    try {
        var transaction = db.transaction(objStore),
            store = transaction.objectStore(objStore),
            request = store.openCursor();

        request.onsuccess = function(evt) {
            var cursor = evt.target.result,
                jsonStr = "";
            if (cursor) {
                var records = cursor.value;
                jsonStr = jsonStr + JSON.stringify(records);
                console.log(jsonStr);
                recordArr.push(records);
                cursor.continue();
            }
        };
        request.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}
/*查询记录根据记录的字段的名
colName:为索引的名字
*/
function queryByColValue(objStore, colName, colValue) {
    var db = localDatabase.db;
    try {
        var transaction = db.transaction(objStore),
            store = transaction.objectStore(objStore),
            index = store.index(colName),
            range = localDatabase.IDBKeyRange.only(colValue),
            request = index.openCursor(range);
        recordArr = [];
        request.onsuccess = function(e) {
            var cursor = e.target.result;
            if (cursor) {
                var record = cursor.value;
                recordArr.push(record);
                console.log(JSON.stringify(record));
                cursor.continue();
            }
        };
        request.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}
/*通过键值获取数据*/
function queryByKey(objStore, key) {
    var db = localDatabase.db;
    try {
        var transaction = db.transaction(objStore),
            store = transaction.objectStore(objStore),
            request = store.get(key);

        request.onsuccess = function(evt) {
            console.log(JSON.stringify(evt.target.result));
        };
        request.onerror = errHandler;
    } catch (e) {
        messageTips(e.message);
    }
}

以上是关于javascript 对索引资料的API简单的包装的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript中对数组和数组API的认识

javascript Console API的便利包装,增加了几个功能。

为 Javascript API 创建飞镖包装器的好方法是啥?

[译]javascript中的依赖注入

在javascript中对数组的索引进行排序

如何仅使用 vanilla JavaScript 和 Node-API 将多个 div 元素包装在另一个元素节点周围?