我将如何创建IndexedDB连接函数而不是编写非DRY代码?

时间:2019-05-31 18:00:19

标签: javascript indexeddb

现在,我有一个js文件建立与IndexedDB数据库的连接。我还有一个用于商店专用功能的js文件。现在,我正在复制将相同的代码粘贴到单独的函数中,并且想知道如何将代码改进为DRY(不要重复自己)。

indexeddb.js

window.webkitIndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

//check for support
if(!window.indexedDB) {
    alert("Your browser do not support indexedDB. Please update you browser.")
}

//open database "KanbanDatabase" version 1. 
//db = database, tx = transaction, store = store data, index = index (seach data).
let request = window.indexedDB.open("KanbanDatabase", 7), 
    db,
    tx,
    store,
    index;

//when creating a new databse, a store(structure) must be added
request.onupgradeneeded = function(e) {
    let db = request.result,
    //tasks
    tasksStore = db.createObjectStore("tasksStore",{
        keyPath: "taskID", autoIncrement: true
    }),
    tasksIndex = tasksStore.createIndex("status", "status", {
        unique: false
    }),
    //members
    membersStore = db.createObjectStore("membersStore", {
        keyPath: "memberID", autoIncrement: true
    }),
    membersIndex = membersStore.createIndex("fullName", "fullName", {
        unique: false
    }),
    //assignments
    assignmentStore = db.createObjectStore("assignmentStore", {
        keyPath: "assignmentID", autoIncrement: true
    }),
    assignmentIndex = assignmentStore.createIndex("assignmentID", "assignmentID", {
        unique: true
    });
};

//open database will return response. 
//error handler:
request.onerror = function(e) {
    console.log("There was an error opening the database: " + e.target.errorCode);
};

//success handler:
request.onsuccess = function(e) {
    console.log("Successfully connected to database.")
    db = request.result;
    //tasks
    tasksTx = db.transaction("tasksStore", "readwrite");
    tasksStore = tasksTx.objectStore("tasksStore");
    tasksIndex = tasksStore.index("status");

    //members
    membersTx = db.transaction("membersStore", "readwrite");
    membersStore = membersTx.objectStore("membersStore");
    membersIndex = membersStore.index("fullName");

    //assignments
    assignmentTx = db.transaction("assignmentStore", "readwrite");
    assignmentStore = assignmentTx.objectStore("assignmentStore");
    assignmentIndex = assignmentStore.index("assignmentID");

    db.onerror = function(e) {
        console.log("ERROR " + e.target.errorCode);
    }

    //close DB conection once transaction is complete.
    tasksTx.oncomplete = function() {
        db.close();
    }

    membersTx.oncomplete = function() {
        db.close();
    }

    assignmentTx.oncomplete = function() {
        db.close();
    }
}

(示例)tasks.js

//add task form function
function addTask() {
    //define user input in the addTaskForm
    var titleInput = document.getElementById("task-title").value;
    var statusInput = document.getElementById("task-status").value;
    var tagInput = document.getElementById("task-tag").value;
    var dueDateInput = document.getElementById("task-dueDate").value;
    var descriptionInput = document.getElementById("task-desc").value;

    //open connection to database
    let request = window.indexedDB.open("KanbanDatabase", 7), 
    db,
    tx,
    store,
    index;

    //error handler on connection
    request.onerror = function(e) {
        console.log("There was en error adding a task: " + e.target.errorCode);
    }

    //success handler on connection
    request.onsuccess = function(e) {
        console.log("Successfully added task to database");
        db = request.result;

        //define transaction, store and index
        tasksTx = db.transaction("tasksStore", "readwrite");
        tasksStore = tasksTx.objectStore("tasksStore");
        tasksIndex = tasksStore.index("status");

        //error handler on result of the request
        db.onerror = function(e) {
            console.log("ERROR " + e.target.errorCode);
        }

        //add new task variables to the database
        let newTask = [{
            title: titleInput,
            status: statusInput,
            tags: tagInput,
            dueDate: dueDateInput,
            description: descriptionInput
        }];

        var addNewTask = tasksStore.add(newTask[0]);

        //success handler on adding member to database handler
        addNewTask.onsuccess = function() {
            console.log("Successfully added task to database");

            let getTasksElementContainer = document.getElementById("list-tasks");
            let createTasksList = document.createElement("li");
            createTasksList.id = "newMember";
            getTasksElementContainer.appendChild(createTasksList);
            createTasksList.innerHTML = JSON.stringify(newTask);
        }

        tasksTx.oncomplete = function() {
            db.close();
        };
    }
}

因此,每次创建新函数时,我都会使用以下代码:

//open connection to database
let request = window.indexedDB.open("KanbanDatabase", 7), 
db,
tx,
store,
index;

//error handler on connection
request.onerror = function(e) {
    console.log("There was en error adding a task: " + e.target.errorCode);
}

//success handler on connection
request.onsuccess = function(e) {
    console.log("Successfully added task to database");
    db = request.result;

    //The stores i use is either this:
    tasksTx = db.transaction("tasksStore", "readwrite");
    tasksStore = tasksTx.objectStore("tasksStore");
    tasksIndex = tasksStore.index("status");

    //or this
    membersTx = db.transaction("membersStore", "readwrite");
    membersStore = membersTx.objectStore("membersStore");
    membersIndex = membersStore.index("fullName");

}

我应该如何对代码的这一部分进行“功能化”?

0 个答案:

没有答案