GotchaCode

Using HTML5 localStorage Into Your App, Check ldb.js

22 Dec 2013

Last night, I was hacking on a small utility library for use when using HTML5 localStorage. When you work with localStorage, it often gets into repetitive state when use use same command again and again. This library just abstracts the process and makes things easier for you. It would work on all modern browsers.

/**
* Ldb.js
* Copyright(c)2013 Vinit Kumar
* MIT Licensed
*/

var Ldb = function () {};

/**
* [check Checks for localStorage support on the browsers]
* @return {[String]} [status of localStorage Support]
*/
Ldb.prototype.check = function () {
if (!localStorage) {
return 'Please use a Modern browser, your browser does not support localStorage yet';
} else {
return 'Bingo, your Browsers supports localStorage, phew!';
}
};

/**
* [get Gives the data stored in the key]
* @param {[String]} key [Key to retrive the data stored in localStorage]
* @return {[JSON]} [The JSON data stored | Error message saying no data stored with that key]
*/
Ldb.prototype.get = function (key) {
if (localStorage.getItem(key)) {
return JSON.parse(localStorage.getItem(key));
} else {
return 'No such key exists, Are you sure you have saved data with the key?';
}
};

/**
* [set Saved data in the localStorage database]
* @param {[String]} key []
* @param {[JSON]} value [The JSON data that gets stored in the localStorage]
*/
Ldb.prototype.set = function(key, value) {
if (typeof (value) === 'object') {
var stringValue = JSON.stringify(value);
localStorage.setItem(key, stringValue);
return 'Successfully saved your data to the key' + key +' key!';
}
};

/**
* [remove description]
* @param {[String]} key [Key for the data to be deleted]
* @return {[String]} [Status message for the remove operation]
*/
Ldb.prototype.remove = function(key) {
if (localStorage.getItem(key)) {
localStorage.removeItem(key);
return 'Successfully removed data with the key'+ key +' !';
} else {
return 'No such key exists, nothing to remove';
}
};



This is all code for the utility as of now. More features are going to flow in coming weeks. Also, you can just install it using 'npm install ldb' or 'bower install ldb.js'. The code is Open Sourced here. https://github.com/vinitkumar/ldb.js

Tweet me @vinitkme if you like this post.

Tweet