Last active
October 5, 2017 15:03
-
-
Save leobetosouza/58b945b4d42d5912d8543f6f5d4c4751 to your computer and use it in GitHub Desktop.
Simple JS Cache Persistence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.cache = (function () { | |
var _data = {}; | |
var _db = openDatabase( | |
'cache.db', | |
'1.0', | |
'app cache database', | |
5 * 1024 * 1024 | |
) | |
function executeQuery (query, values, tx) { | |
values = values || [] | |
return new Promise (resolve, reject) { | |
var exec = function exec (tx) { | |
tx.executeSql( | |
query, | |
values, | |
resolve, | |
reject | |
) | |
} | |
if (tx) { | |
exec(tx) | |
} else { | |
_db.transaction(function (tx) { | |
exec(tx) | |
}, reject) | |
} | |
} | |
} | |
function _save (key) { | |
if (_data[key] != null) { | |
return executeQuery( | |
'INSERT OR REPLACE INTO cache (id, val) VALUES (?, ?);', | |
[ key, JSON.stringify(_data[key]) ] | |
) | |
} else { | |
return Promise.resolve() | |
} | |
} | |
function _remove (key) { | |
return executeQuery('DELETE FROM cache WHERE id = ?;', [ key ]) | |
} | |
function get (key) { | |
return _data[key]; | |
} | |
function set (key, val) { | |
return _save(key).then(function() { | |
_data[key] = val; | |
}) | |
} | |
function del (key) { | |
return _remove(key).then(function () { | |
delete _data[key] | |
}) | |
} | |
function loadDatabase () { | |
return executeQuery( | |
'CREATE TABLE IF NOT EXISTS cache (id TEXT PRIMARY KEY, val TEXT);' | |
) | |
.then(function(tx) { | |
return executeQuery( | |
'CREATE TABLE IF NOT EXISTS cache (id TEXT PRIMARY KEY, val TEXT);', | |
[], | |
tx | |
) | |
}) | |
.then(function(tx, res) { | |
for (var i = 0, l = res.rows.length; i < l; i++) { | |
_data[res.rows.item(i).id] = JSON.parse(res.rows.item(i).val) | |
} | |
}) | |
} | |
return { | |
get : get, | |
set : set, | |
del : del, | |
loadDatabase : loadDatabase | |
} | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment