Created
March 3, 2012 11:05
-
-
Save topliceanu/1965560 to your computer and use it in GitHub Desktop.
store data in localstorage, api similar to document databases
This file contains 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
// stores arrays binded to keys in localstorage | |
(function (win) { | |
var isStorage = function (obj) { | |
return (Object.prototype.toString.call(obj) === '[object Storage]'); | |
}; | |
var decode = function (str) { | |
try { | |
var arr = JSON.parse(str); | |
if (!Array.isArray(arr)) return false; | |
return arr; | |
} | |
catch (ex) { | |
console.log(ex); | |
return false; | |
} | |
}; | |
var store = isStorage(win.localStorage) && win.localStorage; | |
var exists = function (collection, doc) { | |
if (!store) return false; | |
var list = decode(store.getItem(collection)); | |
return (list && list.indexOf(doc) !== -1); | |
}; | |
var save = function (collection, doc) { | |
if (!store) return false; | |
if (exists(collection, doc)) return true; | |
var list = decode(store.getItem(collection)); | |
if (!list) list = [doc]; | |
else list.push(doc); | |
store.setItem(collection, JSON.stringify(list)); | |
return true; | |
}; | |
win.docstore = { save: save, exists: exists }; | |
}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment