Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have a cross platform app created in AngularJS, MOnaca and Onsen UI.

I have implemented a SQLite Database and I can CREATE and INSERT INTO tables using the methods below:

*CREATE

CREATE TABLE IF NOT EXISTS myTable (id, description)

*INSERT

INSERT OR IGNORE INTO myTable (id, description) VALUES (001, 'Some Description')

All that works perfectly - however, I make several API calls to pull data into my tables and want to implement a more elegant and efficient way of doing so.

There are a dozen API calls that I make to create and populate different tables and each one takes on the following format:

E.g. Fruit

[{
    "fruitTable": [{
        "fruitID": "1",
        "fruitDescription": "Apple"
    }]
}]

E.g. Vegetables

[{
    "vegetableTable": [{
        "vegetableID": "1",
        "vegetableDescription": "Broccoli"
    }, {
        "vegetableID": "2",
        "vegetableDescription": "Carrot"
    }]
}]

Each JSON will have a header e.g. fruitTable (which should be the table name) and each item will have a ID (that should be my tables column name e.g. fruitID) and a Description (another column name e.g. fruitDescription). Each JSON can also contain any number of items, but will always take on the format as above.

I have created a function that is called from onDeviceReady() and uses $http to make the API calls (working 100%) to retrieve the JSON data.

var fruitAPIURL = "http://myMadeUpURL/getFruitList.php;
function onDeviceReady()
{
    db = window.openDatabase("myDB", "1.0", "My DB", 200000);
    getAPIDataAndBuildTable(fruitAPIURL );
}

I can loop through the API JSON and create the table and columns as below, but I don't know what the best solution is for getting the column values to INSERT into my table. Do I save them to an array and outside my current loop have another for loop that inserts each value to the table columns? This doesn't seem like the best solution to me. Can anyone suggest a more elegant solution?

function getAPIDataAndBuildTable(apiURL) {
    $http.get(apiURL).then(function success(response) {

        $scope.fruitAPIData = response.data;
        $scope.tableName = "";
        $scope.idColumnName = "";
        $scope.descColumnName = "";

        // Do I create 2 arrays here to hold column values to loop through later to insert into table?
        // $scope.id = {};
        // $scope.desc = {}; 

        $scope.fruitAPIData.forEach(function (dataset) {
            Object.keys(dataset).forEach(function (key) {
                $scope.tableName = key; // Working

                if (Array.isArray(dataset[key])) {
                    dataset[key].forEach(function (item) {
                        angular.forEach(item, function (value, key) {
                            // Get the key for each item and save as column names in table - is there a better way?
                            // How do I save the values as well here to insert later
                            if ($scope.idColumnName == "") {
                                $scope.idColumnName = key;
                            }
                            else if ($scope.descColumnName == "") {
                                if (key == $scope.idColumnName) {
                                    // Do nothing
                                }
                                else {
                                    $scope.descColumnName = key;
                                }
                            }
                        });
                    });
                }
                else {
                    //alert("Dataset[key]: " + dataset[key])
                }
            })
        });

        // Create the Table
        createTable($scope.tableName, $scope.idColumnName, $scope.descColumnName);

        // Insert into the Table - solution below doesnt seem fool proof
        for (var i = 0; i < $scope.id.length; i++)
        {
            insertIntoTable($scope.tableName, $scope.idColumnName, $scope.descColumnName, $scope.id(i), $scope.desc(i));
        }
    },
    function error(response) {
        var data = response.data;
    }); 
}

Create the Table

// Create the Tables 
function createTable(tableName, id, description) {
    var sql = 'CREATE TABLE IF NOT EXISTS ' + tableName + ' (' + id + ' INTEGER PRIMARY KEY, ' + description + ')';
    db.transaction(function (tx) {
        tx.executeSql(sql);
    });
}

Insert into the Table

// Insert into Table
function insertIntoTable(tableName, idColumnName, descColumnName, id, description) {
    var sql = 'INSERT OR IGNORE INTO ' + tableName + ' (' + idColumnName + ', ' + descColumnName + ') VALUES (' + id + ', "' + description + '")';
    db.transaction(function (tx) {
        tx.executeSql(sql);
    });
}

Is there a better and more efficient way of looping through the JSON examples, creating the Tables and inserting values into them for each API call?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.