Skip to content

Instantly share code, notes, and snippets.

@amrishodiq
Created May 10, 2016 10:52
Show Gist options
  • Save amrishodiq/a14b2df0f279f4298dae81a2fc9107dc to your computer and use it in GitHub Desktop.
Save amrishodiq/a14b2df0f279f4298dae81a2fc9107dc to your computer and use it in GitHub Desktop.
JavaScript: LazyRepo, Instantly cache JSON array REST API response into WebSQL.
/**
* Copyright 2016 Amri Shodiq
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Instantly cache JSON array REST API response into WebSQL.
*/
function LazyRepo(config) {
var instance = this;
this.config = config;
this.getAll = function(datasource, callback, errorcallback) {
var sql = "SELECT * FROM "+datasource.table;
query(sql, datasource, callback, errorcallback);
}
this.findBy = function(field, value, datasource, callback, errorcallback) {
var sql = "SELECT * FROM "+datasource.table+" WHERE "+field+" = '"+value+"'";
query(sql, datasource, callback, errorcallback);
}
this.findLike = function(field, valuelike, datasource, callback, errorcallback) {
var sql = "SELECT * FROM "+datasource.table+" WHERE "+field+" LIKE '%"+valuelike+"%'";
query(sql, datasource, callback, errorcallback);
}
var select = function(sql, callback, errorcallback) {
getDatabase().transaction(function(trx) {
trx.executeSql(
sql,
null,
function(trx, results) {
callback(results);
},
function(trx, error) {
callback(null);
errorcallback(error);
}
);
});
}
var db = null;
var getDatabase = function() {
if (db == null) {
db = openDatabase(
instance.config.name,
instance.config.version,
instance.config.realname,
instance.config.size
);
}
return db;
}
var query = function(sql, datasource, callback, errorcallback) {
isDataExists(datasource, function(yes) {
if (yes) {
select(sql, callback, errorcallback);
} else {
$.ajax({
url: datasource.uri,
dataType: 'json',
success: function( result ) {
saveDatas(result, datasource.table, function() {
select(sql, callback);
});
}
});
}
});
}
var saveDatas = function(result, table, onFinished) {
getDatabase().transaction(function(trx) {
result.forEach(function(element, index) {
var sql = createInsertQuery(element, table);
trx.executeSql(
sql,
createInsertValues(element),
function(transaction, sqlResultSet) {
console.log("Succeed");
},
function(transaction, error) {
console.log("SQL: "+sql);
console.log("Error: "+error.message);
}
);
});
onFinished();
});
}
var createInsertValues = function(object) {
var result = [];
var properties = Object.keys(object);
for (var i=0; i<properties.length; i++) {
result.push(object[properties[i]]);
}
return result;
}
var createInsertQuery = function(object, table) {
var sql = "INSERT INTO "+table+" VALUES (";
var properties = Object.keys(object);
for (var i=0; i<properties.length; i++) {
if (i==0) {
sql += "?";
} else {
sql += ", ?";
}
}
sql += ")";
return sql;
}
var isDataExists = function(datasource, callback) {
getDatabase().transaction(function(trx) {
createTableIfNotExists(
datasource,
trx,
function() {
var sql = "SELECT * FROM "+datasource.table;
trx.executeSql(sql, null, function(trx, results) {
if (results.rows.length > 0) {
callback(true);
} else {
callback(false);
}
});
},
function() {
callback(false);
}
);
});
}
var createTableIfNotExists = function(datasource, trx, onSucceed, onError) {
var sql = "CREATE TABLE IF NOT EXISTS "+datasource.table+" (";
var len = datasource.fields.length;
for (var i=0; i<len; i++) {
if (i==0) {
sql += datasource.fields[i];
} else {
sql += ", "+datasource.fields[i];
}
}
sql += ")";
trx.executeSql(
sql,
null,
function(transaction, sqlResultSet) {
onSucceed();
},
function(transaction, error) {
onError();
}
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment